18

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 can successfully post and read 1 value but not multiple values. Here is what I have so far:

jQuery:

var postUrl = "http://localhost:8000/ingredients/";
$('li').click(function(){
    values = [1, 2];
    $.ajax({
        url: postUrl,
        type: 'POST',
        data: {'terid': values},
        traditional: true,
        dataType: 'html',
        success: function(result){
            $('#ingredients').append(result);
            }
    });       
});

/ingredients/ view:

def ingredients(request):
    if request.is_ajax():
        ourid = request.POST.get('terid', False)
        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)

With Firebug I can see that POST contains both ids but probably in the wrong format (terid=1&terid=2). So my ingredients view picks up only terid=2. What am I doing wrong?

EDIT: To clarify, I need the ourid variable pass values [1, 2] to the filter in the ingredients view.

finspin
  • 4,021
  • 6
  • 38
  • 66

5 Answers5

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.

Pablo Abdelhay
  • 988
  • 1
  • 10
  • 12
  • `selected = request.GET.getlist[‌​'selected[]'] TypeError: 'instancemethod' object has no attribute '__getitem__' `I get this error... But i have an array of stings like ["one","two","three"‌​] and am using a `GET` request... – nidHi Aug 17 '16 at 05:10
  • This works, but... why do you need `[]`? The django docs don't reference it at all https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.QueryDict.update – alias51 Mar 31 '20 at 20:05
  • Extremely helpful and still relevant after 8 years! – Rahul May 03 '20 at 21:45
11

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)
finspin
  • 4,021
  • 6
  • 38
  • 66
  • Just an FYI - some older browsers don't have a JSON library built-in. You *might* be better off using `$.serialize` rather than `JSON.stringify` – Josh Smeaton Jun 25 '12 at 00:01
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'))
Josh Smeaton
  • 47,939
  • 24
  • 129
  • 164
  • When I do that I'm getting this error in the ajax callback: TypeError at /ingredients/ 'int' object is not iterable – finspin Jun 24 '12 at 12:17
1

It seems you are setting the array to string here

data: {'terid': values},

It should be

data: {terid: values}
toto_tico
  • 17,977
  • 9
  • 97
  • 116
0

Try sending data like this:

   data: values;
gabberr
  • 357
  • 2
  • 10