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
Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.
To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.
Let's modify the existing code to perform the calculation with JavaScript, client-side rather in server-side with Python. We can also use Ajax to handle the user input rather than rendering a template.
AJAX is a technology for asynchronous execution of HTTP requests from client-side JavaScript code. JavaScript front-end apps use AJAX calls to access the back-end services and APIs and consume data from the Web server over the HTTP protocol.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With