I\'m trying to pass a list of numeric values (ids) from one web page to another with jQuery ajax call. I can\'t figure out how to pass and read all the values in the list. I
You can access this array by request.POST.getlist('terid[]') in the view
in javascript:
$.post(postUrl, {terid: values}, function(response){
alert(response);
});
in view.py:
request.POST.getlist('terid[]')
It works perfect for me.
This part is your problem:
ourid = request.POST.get('terid', False)
ingredients = Ingredience.objects.filter(food__id__in=ourid)
You need to deserialize the JSON string.
import json
ourid = json.loads(request.POST.get('terid'))
It seems you are setting the array to string here
data: {'terid': values},
It should be
data: {terid: values}
Try sending data like this:
data: values;
I found a solution to my original problem. Posting it here as an answer, hopefully it helps somebody.
jQuery:
var postUrl = "http://localhost:8000/ingredients/";
$('li').click(function(){
values = [1, 2];
var jsonText = JSON.stringify(values);
$.ajax({
url: postUrl,
type: 'POST',
data: jsonText,
traditional: true,
dataType: 'html',
success: function(result){
$('#ingredients').append(result);
}
});
});
/ingredients/ view:
def ingredients(request):
if request.is_ajax():
ourid = json.loads(request.raw_post_data)
ingredients = Ingredience.objects.filter(food__id__in=ourid)
t = get_template('ingredients.html')
html = t.render(Context({'ingredients': ingredients,}))
return HttpResponse(html)
else:
html = '<p>This is not ajax</p>'
return HttpResponse(html)