[Answered ]-Django – changing object value and displaying it without reloading

1πŸ‘

βœ…

POST method is more suitable for this request

view

from django.http import JsonResponse

def increaseQuantity(request):
    if request.method == 'POST':
        if request.POST.get("operation") == "increase":
            orderitem = OrderItem.objects.get(id=request.POST.get('orderItem_id', None))
            orderitem.quantity += 1
            orderitem.save()
            return JsonResponse({'count':orderitem.quantity)
    return JsonResponse({'error':'error')

html

{% for product in products %}
    <a href="#" data-orderItemId="{{product.id}}" class = "quantity-increase"><div >Some button content</div></a>
{% endfor %}

#
#
#
$('.quantity-increase').click(function(){
    var orderItemId;
    orderItemId = $(this).attr("data-orderItemId");
    $.ajax({
        type: "POST",
        url: "increase",
        data:{
            orderItem_id:orderItemId,
            csrfmiddlewaretoken: '{{ csrf_token }}',
            'operation':'increase'
        },
        success: function(data) {
                $('.count-of-item').html(data.count) // your results element to show current quantity      
                console.log(data.count)
            },
    })
})
πŸ‘€enes islam

Leave a comment