0

I'm trying to handle ajax POST request using jquery in django project.

but I was encounter an error without specific message.

I have thought some list below that is assumed with error cause.

  1. CSRF-TOKEN that be not included in POST request data

  2. In my javascript code, $.click() method of jquery isn't working.

    ( But actually $.mouseover() method is works. )

    $('#input-submit').click(function() { console.log("before post request!!!"); $.post("/add_to_cart", { product_id : $(this).attr('pro-id'), quantity : $('#input-quan').val() }, function(event) { console.log("success post request!!!"); }, function(error){ console.log("error!!") }); }); 

    shops/static/js/script.js

  3. My form element's usage is wrong.

    <form action="{% url 'shops:add_to_cart' %}" method="post"> {% csrf_token %} <input type="text" id="input-quan"> <input type="submit" id="input-submit" pro-id="{{product.id}}" value="{{product.id}}"> </form> 

    shops/template/shops/product_detail.html

Additionally, This is extra codes.

def add_to_cart(request): quantity = request.POST.get('quantity') product_id = request.POST.get('product_id') return HttpResponse(json.dumps({ "product_id" : product_id, "quantity" : quantity, }),content_type="application/json") # output >>> {"product_id":null, "quantity":null} 

shops/views.py

url(r'^detail/(?P<product_id>[0-9]+)$', views.product_detail, name="detail"), url(r'^detail/add_to_cart$', views.add_to_cart, name="add_to_cart"), url(r'^cart$', views.cart, name="cart"), url(r'^cart/del_from_cart$', views.del_from_cart, name="del_from_cart"), 

shops/urls.py

Although parameters passed to django-view is simple, I'd like to using a POST request.

I'm using django-1.7 version.

Help me please.

1 Answer 1

1

CSRF is activated by default in Django, so in order to use it with jquery ajax requests:

In your JS file:

function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); 

The above will add the CSRF in your request, something that Django expects when you use POST. You can find more information in the official documentation: https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.