7

I am trying to send a JavaScript array to Django via ajax, as follows.

main.html:

<a href=#>Click</a>

<script>
$(document).on('click', 'a', function() {

  var arr = [1, 2, 3, 4];
  var formData = new FormData();
  formData.append('arr', arr);

  $.ajax({
    url: '...',
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false
  });

});
</script>

And on the server side:

views.py:

@csrf_exempt
def main(request):
    arr = request.POST.get('arr')
    print(type(arr))
    print(arr)
    return render(request, 'main/main.html')

the result is a string: '1,2,3,4'.

If I retrieve the data with:

arr = request.POST.getlist('arr')

the result is a list containing a string: ['1,2,3,4']

How can I get a real list like [1, 2, 3, 4]?

8 Answers 8

11

Python 3+, Django 2+, jQuery

In your template

data = {
      key_1_string: 'Value 1 is a string',
      key_2_array: ['1st Value of array', '2nd Value of array'],
      key_3_int: 1234,
      key_4_array_of_objects: JSON.stringify([{id: 3, name: "ABC"}, {id: 4, name: "CBA"}])
      ... rest of your keys/values you want to pass to Server
    }

$.ajax({
    url: "{% url 'ajax_url' %}",
    method : "post",
    dataType : "json",
    data : data,
    timeout: 1000,
    success: function (response) {
        // Do some success scripts
        if (response.operation_status == 'ok') {
            alert ('All done ok')
        } else {
            alert ('Ups. Found some error!')
        }
    },
    error: function (response) {
        // Request error. Display right error message
        ...      
    });

In your view

from django.views.decorators.http import require_POST
from django.http import JsonResponse

@require_POST
def ajax_view_for_ajax_url:
    string_value = request.POST.get('key_1_string')
    array_value = request.POST.getlist('key_2_array[]')
    int_value = request.POST.get('key_3_int')
    array_of_objects = json.loads(request.POST.get('key_4_array_of_objects'))
    
    # Do some magic code with all values
    return JsonResponse({
        'key_1':'value_1',
        'operation_status': 'ok or error',
        ... rest of your keys/values you want to pass to Client
    })

If you don't like jQuery you can send like this

var xhr = new XMLHttpRequest();
xhr.open("POST", "{% url 'ajax_url' %}", true);
xhr.setRequestHeader("X-CSRFToken", formData.csrfmiddlewaretoken);
xhr.onload = function () {
  // do something to response
  var json = JSON.parse(this.responseText);
  if (json.operation_status == "ok") {
    alert ('All done ok');
  } else {
    alert ('Ups. Found some error!');
  }
};
xhr.send(postData);

Hope it helps

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

Comments

6

I finally solved the problem: no [] in JavaScript data, but add [] in Python.

JS:

var arr = [1, 2, 3, 4];

$.ajax({
  url: '...',
  type: 'POST',
  data: {'arr': arr},
});

Python:

arr = request.POST.get('arr[]')

And the result is a list with 4 elements: ['1', '2', '3', '4']

Comments

3

If you want to send an array, you need to append elements a little bit different way:

formData.append('arr[]', arr);

Please check the documentation for more details and examples: https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

5 Comments

The [] in arr[] is just PHP's naming convention. Django doesn't seem to respect that.
Well it is not only a PHP's naming convention, it is a way to send arrays as get parameters as part of URL in http protocol.
But the result of arr = request.POST.get('arr[]') is still a string: '1,2,3,4', and arr = request.POST.getlist('arr[]') is still a list containing one string: ['1,2,3,4'].
in django you have to get result without square brackets: arr = request.POST.getlist('arr')
Or if you work with post requests in django, then in ajax object you have to send data: {'arr': [1, 2, 3, 4]} without formData as mentioned in other answers. And then access this parameter in django normal way without square brackets.
1

You can use without formData.

var arr = [1, 2, 3, 4]

$.ajax({
  url: '...',
  type: 'POST',
  data: arr,
  processData: false,
  contentType: false
})

1 Comment

But request.POST.get('arr') will get nothing?
1

Try to send the array like this:

var arr = [1, 2, 3, 4]

$.ajax({
  url: '...',
  type: 'POST',
  data: {'arr', arr },
  processData: false,
  contentType: false
 })

2 Comments

I suppose it should be a semi-colon as {'arr': arr}. But Django still can not retrieve the array. The result is None.
send your data as json data , remove processData: false , contentType: false and put dataType: 'json'
1

Ok you need few things to take in account first of all you missing csrf_token without Django by default will drop any xhr request

now to normal Django view expect to forms and not to JSON so to get you desired result you code should look like that :

$.ajax({
    type: "POST",
    url: 'http://localhost:8000/test/',
    data: "{ 'a': [1,2,3,4] }",
    contentType: "application/x-www-form-urlencoded/json",
    dataType: "json",
    headers: {"X-CSRFToken":'{{ csrf_token }}'},
    success: function (result) {
        console.log(result.d);
    },
    error: function (result) {
        console.log(result);
    }
});

x-www-from-urlencoded - will threat data as form 

with that code you data will be found in request.POST it you will set

content-type : 'application/json'

you will see the data in body of the request

the usage of set the CSRF Header , if you using you code in Django template you can use it that way if will not you will to parse cookie and set that that in ajax request

i hope it helped

Comments

1

the data that you send should be an object

for example

data = {
a : [1,2,3,4]
}

so

$.ajax({
  url: '...',
  type: 'POST',
  data: data,
  processData: false,
  contentType: false
})

4 Comments

I suppose it should be arr: [1,2,3,4]. But Django still can not retrieve the array. The result is None`.
what the response that you get ??
also content-type should be application/json
Changed to contentType: 'application/json' but requset.POST.get('arr') is still None.
1

in django ,try something like this
in your js file

key=['1','2','3'];
$.ajax({type:'GET',
url:'{% url "function_name " %}',
data:{'arr':key},
success:function(response){
 }
})

and in your view.py ,do something like this

key=request.GET.getlist('arr[]')

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.