views:

45

answers:

2

I'm using django and have a page of search results that I want to be able to filter by category with ajax (jquery) requests. There's a filter bar on the side of the page and when someone selects certain categories and clicks submit, those corresponding results should show up on the page. My code looks something like this:

<input type="checkbox" name="category1" value="1" />
<input type="checkbox" name="category2" value="2" />
<input type="button" name="submit" onclick="{
    var cats = new Array();
    $(input[type=checkbox]:checked).each(function() {
        cats.push($(this).val());
    });
    $.getJSON('page.html', {'cats':cats}, function(data) {...});
}" />

But in the django view when I try to read the cats array it returns a 500 error. I can, however, pass scalars and strings to the django view with no problem.

Any thoughts? Is there a more elegant jQuery way to do this without using a javascript array?

A: 

Rather than getting the field values manually, you can use jQuery's serializeArray() method, which turns a set of fields into an array which can be sent as JSON. Note that you'll probably want both checkboxes to have the same name, so that when it's serialised it becomes something that Django will interpret as a list.

As Steve says, to help further we'll need to know what the view is doing and what the error is.

Daniel Roseman
I tried this and am still getting the same error. You said this creates an array which can be sent as JSON - do I need to then convert it to json before I can send it? I was under the impression that you typically only use json or xml to send data from the server to the page, not the other way around. By the way, I really appreciate the help, this is my first project using either django or ajax :)
danny
A: 

Got it working - I downloaded the jquery-json plugin, encoded my array as a json obect to send to django, and then used simplesjon.loads() in the django view to convert that json object to a python list. However, the fact that it took so many steps and jQuery on its own doesn't even come with json encode functionality still makes me think there must be a more elegant way - if anyone has any insight, I'd love to hear it.

Thanks Daniel for pointing me in the right direction.

danny