Django context variables and ajax response

I am working on a basic search for my blog, and the main functions work and work. However, I am wondering if you can return context variables in the ajax response, which you can then get in the template. Here is my def search:

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 want to do is pass the query variable contained in def search back to my jquery function. In your regular HTTP response, you should use context variables ... but I'm not sure how this can be conveyed using jQuery.

+5
source share
1 answer

What you can do is translate the dictionary back to HttpResponse, not 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')

Be sure to import json or simplejson.

+3
source

All Articles