B
B
BotaniQ_Q2018-02-14 17:18:18
Django
BotaniQ_Q, 2018-02-14 17:18:18

Django ajax problem?

There is a form

<form class="f-basket" action="{% url 'add_basket' %}">{% csrf_token %} 
  
  Сколько?
  <input type="number" class="number">

  <button  type="submit"  class="submit_btn" data-text = "Здесь просто текст">Отправить</button>


</form>


I have jquery code
$(document).ready(function(){
        var form = $('.f-basket');
        form.on('submit', function(preventdefault){
        preventdefault.preventDefault();
        var submit_btn = $('.submit_btn');
        var text = submit_btn.data("text")
        var nmb = $('.number').val();
        console.log(text, nmb)




        var data = [];
        data.text = text
        data.nmb = nmb;


        var csrf_token = $('.f-basket [name="csrfmiddlewaretoken"]').val();
        data["csrfmiddlewaretoken"] = csrf_token;

        var url = form.attr("action");

        console.log(url)


        console.log(data)

        $.ajax({
             url: url,
             type: 'POST',
             data: data,
             cache: true,
             success: function () {
                 console.log("OK");

             },
             error: function(){
                 console.log("error");
             }
         })

        
        $('.basket-container ul').append('<li>'+text+ ' в количестве '+ nmb + 
            '<a class="delete-item" href="#">x</a>'+ '</li>');


     });

    $(document).on('click', '.delete-item', function(preventdefault){
         preventdefault.preventDefault();
         $(this).closest('li').remove();
     })

    

    });


And there's a performance
def add_basket(request):
  return_dict = dict()
  session_key = request.session.session_key
  if not session_key:
    request.session.cycle_key()

  

  print(request.POST)

  return JsonResponse(return_dict)


All dates are displayed in the browser console, but it shows that the server is not processing the request and throws an error in the browser, in the django console it says that the csrf token is lost or incorrect, but in the browser, along with other data, the token is also issued, what's the problem here?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-14
@BotaniQ_Q

The documentation has a whole section about it .

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question