javascriptjquerydjangoajaxshopping-cart

Ajax is not working without refreshing the page


Ajax is not working without refreshig the page to make it work.I am coding an ecommerce website in django and need to show quantity of products in the cart but it dont show quantity without refresh the page.

        <script>
            $(document).on("click", "#add_button", function (e) {
                e.preventDefault();
                $.ajax({
                   type: "POST",
                   url: "{% url "add_cart" %}",
                   data: {
                     product_id: $("#add_button").val(),
                     csrfmiddlewaretoken: "{{ csrf_token }}",
                     action: "post",
                   },
                    success: function (json) {
                        {#console.log(json)#}
                        document.getElementById("cart_quantity").textContent = json.qty
                    },
                    error: function (xhr, errmsg, err) {

                    }
                });
                
            })
        </script>
class Cart:
    def __init__(self, request):
        self.session = request.session
        cart = self.session.get("cart_key")
        if cart is None:
            cart = self.session["cart_key"] = {}
        self.cart = cart

    def add(self, product):
        product_id = str(product.id)
        if product_id in self.cart:
            pass
        else:
            self.cart[product_id] = {"Price: ": str(product.price)}
        self.session.modified = True

    def __len__(self):
        return len(self.cart)
def add_cart(request):
    cart = Cart(request)
    if request.POST.get("action") == "post":
        product_id = int(request.POST.get("product_id"))
        product = get_object_or_404(Product, id=product_id)
        cart.add(product=product)
        cart_quantity = cart.__len__()
        # response = JsonResponse({"product name: ": product.name})
        response = JsonResponse({"qty: ": cart_quantity})
        return response
<p id="cart_quantity" >{{ cart|length }}</p>

my shopping button show this when i add a product and when i refresh show the quantity enter image description here


Solution

  • I think the problem is due to a mismatch between the key in the JSON response from your Django view and what your ajax js is trying to access on your target somehow. (api...). And why I think so: Your code:

    def add_cart(request):
     cart = Cart(request)
     if request.POST.get("action") == "post":
     product_id = int(request.POST.get("product_id"))
     product = get_object_or_404(Product, id=product_id)
     cart.add(product=product)
     cart_quantity = len(cart)
     response = JsonResponse({"qty:": cart_quantity}) # Key is "qty:"
     return response
    

    I saw the key in the JSON response is "qty:" and not "qty" and you are trying to access your json with "json.qty" according to this code:

    success: function (json) {
     document.getElementById("cart_quantity").textContent = json.qty; // Trying to access "qty"
    }
    

    and not according to what you defined before "qty:" In other words: qty from json does not match the key "qty:". (with a colon). And in the end you will probably get "undefined" from qty because you tried to access it and not the correct "qty:" (the key the correct and original one in your code). If you add (to see the error) console.log(json); before

    document.getElementById("cart_quantity").textContent = json.qty;

    In such a function

    success: function (json) {
     console.log(json); // Log the JSON response
     document.getElementById("cart_quantity").textContent = json.qty;
    }
    

    You will see { "qty:": 5 // The key includes a colon } and not according to what you wanted without it. (qty without colon).

    Solution is: Delete the colon from qty. Because of the mismatch in json that I explained earlier. This is the correct code:

    def add_cart(request):
    cart = Cart(request)
    if request.POST.get("action") == "post":
    product_id = int(request.POST.get("product_id"))
    product = get_object_or_404(Product, id=product_id)
    cart.add(product=product)
    cart_quantity = len(cart)
    response = JsonResponse({"qty": cart_quantity}) # Key is "qty" without colon
    return response