[Fixed]-Passing list of values to django view via jQuery ajax call

12👍

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)

49👍

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.

3👍

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'))

1👍

It seems you are setting the array to string here

data: {'terid': values},

It should be

data: {terid: values}

0👍

Try sending data like this:

   data: values;

Leave a comment