0

Generic Javascript POST for Django Ajax

When building Raspberry Pi interfaces or ordinary websites with Django, it is often preferable to prevent site redirects, since the user interactions are smoother without. This can be done via JavaScript/JQuery Ajax POST requests. Since a lot of these Ajax requests are necessary in larger applications, it is helpful to have a generic JavaScript Ajax POST function.
The following universal POST function can gather data as required from the website, send it to a custom Django view, let do Python the processing, return the result and apply a custom JavaScript function on success.

So, this JS function takes arbitrary data as a JavaScript dictionary, POSTs it to the url parameter and executes a success function on success, for example:

Here’s and example how the generic POST could be called:

This needs an input with the id temperature and a csrf token from Django.

The url needs to be defined in urls.py:

And there needs to be a function in views.py that returns a JSON response:

Knight of Pi

Johannes Bergs aka Knight of Pi. Diploma in Bioinformatics, some Webdesign and Python coding then. Living in the beautiful city of Vienna.

Comment

Time limit is exhausted. Please reload CAPTCHA.