2

I'm trying to send array as a parameter to the api which is using python and django framework.

Here's my client side code that is being used to access the api:

$.ajax(
    type: 'POST',
    url:    'http://example.com/api/users',
    data:   {user:{name:'Rohit Khatri', age:20, father_name:'S.K'},type:'info'},
    complete: function(response) {
        console.log(response);
    }
);

Here's the view where I'm trying to access the request parameters

def get_users(request):
    print(request.POST.get('ids'))

and when I try to access ids parameter, It gives None. If anyone has faced the same problem, please help me.

Rohit Khatri
  • 1,980
  • 3
  • 25
  • 45
  • Possible duplicate of [How to get an array in Django posted via Ajax](http://stackoverflow.com/questions/12101658/how-to-get-an-array-in-django-posted-via-ajax) – e4c5 Nov 23 '16 at 06:48

1 Answers1

8

You can try getting the list as follows:

request.POST.getlist('ids[]')

Note: You will be better off if you send/receive your data as JSON. You first need to set the Accept and Content-Type headers to application/json while sending the request and then convert the json to python object using json.loads. Example as follows:

Javascript/AJAX

$.ajax(
    type: 'POST',
    url:    'http://example.com/api/users',
    contentType: 'application/json'
    data:   {ids:[1,2,3,4,5],type:'info'},
    complete: function(response) {
        console.log(response);
    }
);

Django

import json

def get_users(request):
    ids = request.POST.get('ids')
    if ids:
        ids = json.loads(ids)

Update:

In case you need to use more complicated data such as an object (dictionary) using json will be your best bet and it will work pretty similar to the above example.

Javascript/AJAX

$.ajax(
    type: 'POST',
    url:    'http://example.com/api/users',
    contentType: 'application/json'
    data:   {ids:{"x":"a", "y":"b", "z":"c"}, type:'info'},
    complete: function(response) {
        console.log(response);
    }
);

Django

import json

def get_users(request):
    ids = request.POST.get('ids')
    if ids:
        ids = json.loads(ids)
Amyth
  • 32,527
  • 26
  • 93
  • 135