bento
bento

Reputation: 5026

Django context variables and ajax response

I'm working on a basic search for my blog, and the basic functionality is up and working. What I'm wondering, however, is if you can return context variables in an ajax response, which could then be accessed in the template. Here's my search def:

from django.http import HttpResponse
from django.db.models import Q
from django.core import serializers

def search(request):
    if request.is_ajax():
        query = request.POST['query']
        text_list = Text.objects.filter(Q(title__icontains=query) | Q(mytextfield__icontains=query))
        data = serializers.serialize("json", text_list)
    else:
        data = "whoops"
    return HttpResponse(data,'application/javascript')

This is requested through jquery.

$(document).ready(function() {
    $('#search').submit(function(){
        $.post("/search/search/", $("#search").serialize(), function(data){
            // Search results for: **query**
            $.each(data, function(index){
                $(ajax).append(data[index].fields.title + "<br>");
            }); 
        }, "json"); 
        return false
    });
});

What I'm wanting to do is pass the query variable, contained in def search, back to my jquery function. In a regular http response, you'd use context variables... but I'm not sure how those could be passed with jQuery.

Upvotes: 5

Views: 3168

Answers (1)

Jordan
Jordan

Reputation: 32552

What you can do is pass a dictionary back to your HttpResponse instead of just the results.

data = {
    'query': request.POST['query'],
    'results': serializers.serialize("json", Text.objects.filter(Q(title__icontains=query) | Q(mytextfield__icontains=query)))
}

return HttpResponse(json.dumps(data), 'application/javascript')

Make sure to import json or simplejson.

Upvotes: 3

Related Questions