1

I met some problems when I try to send the POST request using ajax in Django. I already research some topics here, but still can't find the way to solved them.

Here is my javascript code that follow this solution:

$.ajax({
    url: '{% url home %}',
    data: {selected_folders: formData,
           csrfmiddlewaretoken: '{{ csrf_token }}'},
    dataType: "json",
    type: "POST",
});

I also try the solution from Django

$("form").submit(function() {
    var csrftoken = $.cookie('csrftoken');
    $.ajax({
        url: '{% url home %}',
        data: {selected_folders: formData,
               csrfmiddlewaretoken: csrftoken},
        dataType: "json",
        type: "POST",
    });
});

Here is my view.py

def home(request):        
    if request.method == 'POST':
        Call_Other_Class()
    return render_to_response('home.html')

My goal is to send the POST request from home.html to itself, and when home.html get the POST request, it will call other classes to do something else. I am not sure where to put the CSRF token in the template and if my code in view.py is correct or not.

Thanks for your reading and solve my problems.

Edit:

I edited my javascript code to:

<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
      var csrftoken = Cookies.get('csrftoken');
      function csrfSafeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }
      $.ajax({
        url: '{% url home %}',
        data: {selected_folders: formData},
        beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
        },
        dataType: "json",
        type: "POST",
      });
    });
</script>

HTML:

<form>
  <ul>
    <li id='key1'></li>
    <li id='key2'></li>
  </ul>
</form>

still doesn't work.

Jimmy Lin
  • 1,481
  • 6
  • 27
  • 44

2 Answers2

2

For Js:

$("form").submit(function() {
   $.ajax({
       url: '{% url home %}',
       data: {selected_folders: formData,
           csrfmiddlewaretoken: $("[name = csrfmiddlewaretoken]"),
        dataType: "json",
        type: "POST",
    });
});

For view.py:

def home(request):        
if request.method == 'POST' and request.is_ajax():
    Call_Other_Class()
return render_to_response('home.html')
hizbul25
  • 3,829
  • 4
  • 26
  • 39
0

The best solution is using the online documentation. From what I recall:

  • first call a GET in Ajax and in the answer, force ensure_csrf_cookie decorator
  • then keep the CSRF cookie, you have all the detail explanation here.
Olivier Pons
  • 15,363
  • 26
  • 117
  • 213