1

Nothing will ne happened when I submit product in the the cart. I want to use AJAX without refreshing page. When I submit the console message will be displayed. I'm trying to use AJAX first. Trying to add product in the cart without refreshing page. I need 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 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>

JS Code

        $(".buy-product").on('click', function(e){
            e.preventDefault();
            var product_id = $(this).attr('data-id')
            var quantity = 1
            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',


                data: data,

                success: function(data){
                    console.log('success')
                    console.log(csrftoken)
                    
                }
        })
    })


Seydina
  • 61
  • 1
  • 7

2 Answers2

0

You need to add csrftoken in data: {csrfmiddlewaretoken':csrftoken}. Also I don't see when you initialize your variables, but I think is just example. Check this answer for more: link

mka
  • 153
  • 5
  • I have error 500 when I click add is_ajax method in my views. – Seydina Feb 05 '21 at 13:09
  • Just one think. I've just seen that you put into data `point` hardcoded url with some id. In your case it is not necessary to put `product_id` parameter, but if you prefer to stay with that just check this [answer](https://www.semicolonworld.com/question/70080/how-to-pass-parameter-to-ajax-urls-django). I want to notice that your way to solve the problem is much harder than just deleting url `product_id` parameter. Look that you are already sending this variable in data. Why duplicate that? – mka Feb 05 '21 at 19:33
0

You can prevent form from refreshig the page and then do whatever you need with your JS code:

<form action="{% url "..." %}"  method="post" data-id="{{ ... }}" class="form-order" id="form" onsubmit="myFunction(event)">
...
</form>
<script>
function myFunction(event){
    event.preventDefault();
}
</script>
Charnel
  • 4,222
  • 2
  • 16
  • 28
  • Nothing will be happened when I do this. – Seydina Feb 05 '21 at 12:52
  • That's actually what it's doing - prevent the default behavior for form on submit, including page reload, and let's you handle it yourself in whatever way you need. – Charnel Feb 05 '21 at 13:55
  • How to prevent the default behavior of the form? PreventDefault allows not to reload the page. – Seydina Feb 05 '21 at 16:42
  • Default behavior of the form is sending post request, after click on submit button, that causing page reload. When you use `preventDefault` you are left on your own with sending post request and hadling response. – Charnel Feb 07 '21 at 10:03