[Answer]-Ajax JSON response not working


The problem you’re facing is that you’re trying to update a Django template compiled variable called context_list this won’t happen magically by using AJAX since Django has precompiled the HTML you’re serving when you hit the page initially.

You can’t circumvent this but you can work around it and below I’ll show you two ways of doing it.

Your success() handler in your jQuery script that you have that manages the search gets the newly HTML that you’ve recompiled but you’re not using it anywhere ergo, it won’t work.
In this case you’re just logging some stuff out to console. (This would be where you’re using option #2.)

You have two options as I see it. (It’s a lot of code so I’ll give you the pointers and not the implementation, won’t strip you of all the fun!)

I’ll give you a quick run down of both and then you can decide which way you want to take.

  1. You can use jQuerys $.load() method in order to fetch a
    recompiled template.
  2. You can use $.getJSON() and get the
    objects in JSON format and then update the HTML accordingly.

First option – $.load()

def search_view(keyword, request):
   search_result = SearchModel.objects.filter(some_field=keyword)
   t = loader.get_template("some_result_template.html")                
   c = Context({'search_results':search_result})
   return render(t.render(c))

$("#result").load("url_to_your_search", { 'keyword': 'search_me' } );

Second option – $.getJSON()

from django.core import serializers

def search_view(keyword, request):
    search_result = SearchModel.objects.filter(some_field=keyword)
    json_data = serializers.serialize('json', search_result)
    return HttpResponse(json_data, mimetype='application/json')

$.getJSON('url_to_your_search_view', { keyword: "search_me" }, function(json_data) {
  var items = [];

  $.each(json_data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')

Now the JSON code is taken straight from the docs, so you would have to modify it but you get the gist of what’s needed in order for yours to work.

Leave a comment