2

I am trying to send via AJAX an array (or object) to my Django View.

In JS File:

    var dataArr = [];
    dataArr.push({'status':'active'});
    ...
    var json = JSON.stringify(dataArr);
    ...
    $.ajax({
        type: "POST",
        url: "/filter/",
        data: {
            'filter_text' : json,
            'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
        },
        success: filterSuccess,
        dataType: 'json',
        contentType: 'application/json'
    });

I am getting a 403 Forbidden error in Javascript. I tried several things, e.g. omitting the dataType / contentType, sending a Javascript object instead of an array, etc.

4
  • 1
    Do you pass csrf token to your post request? Or use csrf_exempt? Commented Oct 9, 2018 at 14:22
  • Try to add @csrf_exempt decorator to your view and if it will work - the problem is in $("input[name=csrfmiddlewaretoken]").val(). Are you sure the token is being sent at all? Try to use console.log($("input[name=csrfmiddlewaretoken]").val()) before ajax method. Commented Oct 9, 2018 at 14:28
  • 2
    You can just add 'csrfmiddlewaretoken': '{{ csrf_token }}' Commented Oct 9, 2018 at 14:30
  • The middleware token was already there. I am simply using the following ajax call and am using the array itself - this did the trick for me: $.ajax({ type: "POST", url: "/filter/", traditional: true, data: { 'status_filter' : statusArr, 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: filterSuccess, }); Commented Oct 9, 2018 at 22:34

1 Answer 1

1

You can't pass the array directly to url,

Use jQuery.param(yourObject).

The param() method creates a serialized representation of an array or an object that can be understandable by various frameworks like php, ruby, django etc.

For again converting it to python

from urllib import parse
value = parse.parse_qs(self.request.POST.get('name'))

Note that using prase you can lost some information, so recheck your data after getting it in python.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.