tags:

views:

1021

answers:

6
+6  Q: 

Django + Ajax

So, I am just starting to use jQuery with one of my Django projects, but I have a pretty noobie question.

In a django view you have to return an HttpResponse object from the view, but sometimes I don't need to return anything. For instance, I might just be updating the database via ajax and don't need to send anything back. So my question is, what do you do in that situation?

Thanks

A: 

I'd return a empty string:

return HttpResponse("")
Tiago
+5  A: 

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.

Jason Christa
+19  A: 

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.

Ionuț G. Stan
A: 

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
I believe 201 means you created something, and then you could return a 200 if you just move something around.
Jason Christa
A: 

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,

Boldewyn
A: 

hi Joe, did you solve your issue ?

ali