Click here to Skip to main content
15,867,321 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to use ajax to update my cart without reloading the page, I have a view that's working fine in the backend, it prints "success 20" (20 as in cartItems) as expected but the ajax function prints literally "{{request.cartItems}}" success yet not the actual number, I'm trying to print out the cartItems in the console and eventually update the nav as in when someone hits add-to-cart from the template without reloading, it just updates {{cartItems}} in real time. Can someone please help me out I would really appreciate that!
JavaScript


What I have tried:

views.py
def ajax_update(request):
	data = cartData(request)
	cartItems = data['cartItems']
	if is_ajax and request.method == "GET":
		if cartItems:
			print("success", cartItems)
			data_attribute = request.GET.get(cartItems)
		return JsonResponse(data_attribute, safe=False, status=200)
	else:
		print("fail")
	context = {"cartItems": cartItems}
	return render(request, 'store/shop.html', context)


urls.py

Python
path('ajax_update/', views.ajax_update, name="ajax_update"),

js

var cartData = '{{request.cartItems}}'
function ajax_update_CartData() {
    $.ajax({
        headers:{
        'Content-Type':'application/json',
        'X-CSRFToken':csrftoken,
        },
        url: 'ajax_update/',
        type: 'GET',
        data : cartData,
        success: function(data){
            console.log('success')
            console.log(cartData)  
        }
    })
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900