DGDD
DGDD

Reputation: 1390

Loading Django template using AJAX html() resulting in unwanted text

I am loading a template via Ajax.

This is what it looks like client side:

function AJAX_query(query_JSON){
    $.ajax({
        type: 'GET',
        url: '/ajax_request/',
        data: query_JSON,
        datatype: "json",
        success: function(data){
            $("#search_results").html(data);
        },//success
        error: function(){
            alert("AJAX - failure.");
        }//error
    });//.ajax
};//AJAX_query

Back at the server I have a simple template render with pagination.

def Selector_Query(request, query):
   query = query.split(",")
   # Filter model based on query
   some_models = Some_Model.objects.all().filter(whatever = query[n])

   # PAGINATION
   paginator = Paginator(some_models, 30)

   try:
        some_models = paginator.page(query[n])
   # If page is not an integer, deliver first page.
   except PageNotAnInteger:
        some_models = paginator.page(1)
   # If page is out of range (e.g. 9999), deliver last page of results.
   except EmptyPage:
       some_models = paginator.page(paginator.num_pages)

   last_page = paginator.num_pages

   context = RequestContext(request, {
      "some_models":some_models,
      "last_page":last_page,
      "page_number":query[n],
   })

   template = loader.get_template("some_folder/some_template.html")
   return HttpResponse(template.render(context))

When I receive the data there is always this at the top:

Content-Type: text/html; charset=utf-8

If I use load() instead of html(), the above does not appear anymore. However, as I understand, I cannot use load as load() needs a url and I would rather work without a url because of the complex parameters that I am sending. Hence the whole reason for AJAX in the first place.

Any idea why this is happening, and how I should resolve it?

Upvotes: 1

Views: 1379

Answers (1)

DGDD
DGDD

Reputation: 1390

Found the problem. It's the

return HttpResponse(template.render(context))

needs to be

    return render_to_string("some_folder/some_template.html", context)

Upvotes: 1

Related Questions