Skip to content

Commit

Permalink
3 - Handle Ajax in Django with JsonResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
codingforentrepreneurs committed Oct 6, 2017
1 parent 1d4d7ca commit d6acdc2
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
13 changes: 11 additions & 2 deletions src/carts/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.http import JsonResponse
from django.shortcuts import render, redirect


Expand All @@ -19,8 +20,7 @@ def cart_home(request):

def cart_update(request):
product_id = request.POST.get('product_id')
if request.is_ajax():
print("Ajax request")

if product_id is not None:
try:
product_obj = Product.objects.get(id=product_id)
Expand All @@ -30,10 +30,19 @@ def cart_update(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
added = False
else:
cart_obj.products.add(product_obj) # cart_obj.products.add(product_id)
added = True
request.session['cart_items'] = cart_obj.products.count()
# return redirect(product_obj.get_absolute_url())
if request.is_ajax(): # Asynchronous JavaScript And XML / JSON
print("Ajax request")
json_data = {
"added": added,
"removed": not added,
}
return JsonResponse(json_data)
return redirect("cart:home")


Expand Down
Binary file modified src/db.sqlite3
Binary file not shown.
2 changes: 2 additions & 0 deletions src/products/templates/products/snippets/update-cart.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
{% if in_cart %}
<button type='submit' class='btn btn-link btn-sm' style="padding:0px;cursor: pointer;">Remove?</button>
{% else %}
<span class='submit-span'>
{% if product in cart.products.all %}
In cart <button type='submit' class='btn btn-link'>Remove?</button>
{% else %}
<button type='submit' class='btn btn-success'>Add to cart</button>
{% endif %}
</span>
{% endif %}
</form>
8 changes: 6 additions & 2 deletions src/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,12 @@
method: httpMethod,
data: formData,
success: function(data){
console.log("success")
console.log(data)
var submitSpan = thisForm.find(".submit-span")
if (data.added){
submitSpan.html("In cart <button type='submit' class='btn btn-link'>Remove?</button>")
} else {
submitSpan.html("<button type='submit' class='btn btn-success'>Add to cart</button>")
}
},
error: function(errorData){
console.log("error")
Expand Down

0 comments on commit d6acdc2

Please sign in to comment.