43Tesseracts 43Tesseracts - 4 months ago 24
JSON Question

How to pass an HttpResponse and additional data via Ajax in Django

I have two different AJAX requests that I want to combine.

The first one gets some html:

def ajax_get_html(request):
if request.is_ajax() and request.method == "POST":
context = {
...
}
return render(request,"my_app/my_template.html", context)
else:
raise Http404


And is used like this:

$.ajax({
type: "POST",
url: ajax_url,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
$(my_div).html(data);
}
});


My second one gets some data:

def ajax_get_data(request):
if request.is_ajax() and request.method == "POST":
data = {
"answer": 42,
}
json_data = json.dumps(data)
return HttpResponse(json_data, content_type='application/json')
else:
raise Http404


and is used like this:

$.ajax({
type: "POST",
url: another_ajax_url,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
var answer = data.answer;
$("#notification_badge").html(answer);
}
});


How can I combine these to into the same request? I tried adding the result of
render
to the data in the second view, but json.dumps says it's non serializable.

Answer

You can't serialize the output of Django's render because it returns an HttpResponse object, not a string (which is what you want to be able to serialize it).

A good solution is to return your html to the frontend using render_to_string:

...
data = {
    "answer": 42,
    "html": render_to_string("my_app/my_template.html", context)
}
...
Comments