Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing list of values to django view via jQuery ajax call

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.

like image 368
finspin Avatar asked Jun 24 '12 10:06

finspin


People also ask

How do I get data from my AJAX post to my Django view?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

How send data from AJAX to Django?

1 Answer. Show activity on this post. // wrap request in a function: function send_data() { $. ajax({ url : 'the_url', data : { 'csrfmiddlewaretoken' : '<the-token>', 'key1' : 'val1', }, method : 'POST', success : success_function // reference to below }); } // trigger send_data on some event: $('<the-selector').

Can I use AJAX in Django?

Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.


1 Answers

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.

like image 193
Pablo Abdelhay Avatar answered Sep 28 '22 04:09

Pablo Abdelhay