max max - 6 months ago 19
jQuery Question

Receiving ajax posted object in django view

needless to say i'm a rookie ! so here is my js code which send a js object via ajax to a view

function test(){
arr = {} ;
$('#settings_tab').find('.someclass').each(function(index, element) {
key = $(this).attr('id') ;
value = $(this).val();
arr[key] = value;
});

$.post("{% url 'setting-update' %}",
{arr:arr, csrfmiddlewaretoken: '{{ csrf_token }}'},
function(){
alert('done!');
}
);
}


posted data in firebug looks like this

arr[adminName]
arr[contactAddress]
arr[contactEmail]
arr[contactPhone]
arr[perPage]
arr[siteDisableMsg]
arr[siteTitle]
arr[uploadSize]
csrfmiddlewaretoken BFrb8snw8zime8UI8Vukl8FirsHvDDUk


heer is my django view.py

def update(request):
if request.POST :
print('-------------------------------------------------')
print(request.POST)
arr = request.POST.getlist('arr', None)
print(arr)
if(arr is not None):
for k,v in arr:
print(k)

return HttpResponse('done !')


but in this line

arr = request.POST.getlist('arr', None)
print(arr)


keep getting
[]
... how can i get
arr
from POST ?

btw in the console when i print POST i get something like this

<QueryDict: { 'csrfmiddlewaretoken': ['BFrb8snw8zime8UI8Vukl8FirsHvDDUk'], 'arr[adminName]': [''],
'arr[uploadSize]': [''], 'arr[adminName]': [''], 'arr[contactEmail]': [''], 'arr[siteTitle]': [''], 'arr[perPage]': ['']}>

Answer

Two things to take note of there, first of all, JQuery is flattening your data-structure. For each element in your dictionary (that is, your arr variable), it creates a element in the QueryDict with a unique key.

So,

var arr = {'one': 'data1', 'two': 'data2'};

becomes

<QueryDict: {'arr[one]': 'data1', 'arr[two]': 'data2'}>

Which is very much aligned with what you are seeing. However, in your case, it doesn't actually seem like you are populating the array with values. Both your firebug and QueryDict output insinuates yu have a empty dictionary. I would investigate what value is in the following line of your javascript

value = $(this).val();

Also, you are using getlist() wrong, it gives you a list associated to a key in QueryDict, it doesn't give you a dictionary as you are expecting it to.

What you wan't to explore is the following, first serialise your array with JSON.stringify() as follows:

$.post("{%  url 'setting-update' %}" , { 'arr': JSON.stringify(arr), csrfmiddlewaretoken :  '{{ csrf_token }}' });

and then convert it to a python dict in the view by

import json
yourdict = json.loads(request.POST.get('arr'))