Update quantity of cart after add product to cart AJAX / Django without refreshing page?

Viewed 200

The product is successfully added in the cart but the cart value is not up to date. I will have to refresh the page so that the div is up to date. I tried the load() and html() methods but anything will happened. How to refresh cart container when I add the product to the cart ? I need a help please.

Views Django

def add_cart(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)

    form = CartProductForm(request.POST)
       
    if form.is_valid():
        cd = form.cleaned_data
        cart.add(product=product,
                quantity=cd['quantity'],
                update_quantity=cd['update_qt']
                )
                
    return JsonResponse({'status': 'success'}) 

Form

from django import forms
from django.core.validators import MinValueValidator, MaxValueValidator

class CartProductForm(forms.Form):
    quantity = forms.IntegerField(initial=1)
    update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)

HTML Form Code

<form action="{% url "..." %}"  method="post" data-id="{{ ... }}" class="form-order" id="form">
    {{ cart_product_form }}
    {% csrf_token %}
    <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a>
</form>

HTML Span

<ul class="navbar-nav ml-auto d-block d-md-none">
      <li class="nav-item">
        <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a>
      </li>
</ul>

JS Code

        $(".form-order").on('submit', function(e){
            e.preventDefault();
            var product_id = $(this).attr('data-id')
            var quantity = $(this).find("#id_quantite").val()
            console.log(product_id)
            console.log(quantity)

            data = {
                'product_id': product_id,
                'quantity': quantity
            }
            var point='/cart/add/'+product_id+'/'
            
            $.ajax({
                headers:{
                'Content-Type':'application/json',
                'X-CSRFToken':csrftoken,
                },
                url: point,
                type: 'POST',
                dataType: 'json',
                data: data,

                success: function(data){
                    $("cartval").load();
                    $("#cartval").load(location.href + " #cartval");
                    
                }
        })
    })


0 Answers
Related