Django + Ajax Django + Ajax django django

Django + Ajax


An HTTP response is more than sending content to the browser. A response is associated with a status code and several HTTP headers. Additionally, a response may contain a body (actual content).

I think it's OK to sent an HttpResponse object with no body. That is:

return HttpResponse()

This will send an HTTP response with status code 200 OK, which is exactly what happened on the server side, i.e. the operation succeeded, everything is OK. Although there are better ways, see below.

Restfully speaking, when the operation encountered problems, you should return an HTTP response with an appropriate status code. Like one of the 5XX status codes which designate server side errors.

Now, looking at all those HTTP status codes we see a 201 Created status code which is a more appropriate code than 200 OK when you're storing that POST data somewhere, like a DB. In this case you should be doing something like this in your view:

return HttpResponse(status=201)

And, as someone already mentioned, you could take advantage of these status codes in your JavaScript so that you can present a user a more informative message or maybe choose some other strategy for your requests.


You still want to return an HttpResponse to let jQuery know whether the response was a success or failure. Most javascript libraries includeing jQuery are looking for a 200 ok response. Not to mention it might be useful to return a JSON object with number of rows affected or tally of a vote.


I'd return a empty string:

return HttpResponse("")