[Django]-Django + Ajax

37👍

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.

5👍

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.

0👍

I’d return a empty string:

return HttpResponse("")
👤Tiago

0👍

Thanks for the answers. The example I am currently working on is a todo list, where the user can drag items to a new position. I’m using jQuery to send post data to the view, which saves the new order in the database. For this example, I don’t want to show a response to the user after they have resorted the list because it would get annoying and it’s not really necessary. I will be catching any errors if they occur and showing the user an appropriate response if that happens.

So using return HttpResponse(status=201) is a good idea in this scenario?

👤Joe

0👍

Sorry, can’t comment yet.

HTTP status codes are a great way for adding additional info (like demonstrated by REST). See here for the ones that are not 200, 404 or 500:

RFC2616

Cheers,

Leave a comment