How to Perform an AJAX GET Request in Django with jQuery



Python


In this article, we show how to perform an AJAX GET request in Django with jQuery.

With an AJAX GET request, we can get any type of data we want, usually it's getting data from one of the databases you've created. You may want to get data from a user, or get the number of page views the page has, etc. However, you really can get data from any source such as another website.

The point and value of an AJAX GET request is that you can get any data you want asynchronously- which requires no page refresh.

Getting data without page refreshes is the whole point of AJAX. It creates a better a user experience for visitors on your website.

So how can we incorporate AJAX into our Django website to perform GET requests, so that we do not have to refresh pages for data that we display on the page?

So let's say we want to retrieve the number of page views a page has received using AJAX (by the time the user clicked the page and all elements have downloaded).

The value of these page views is stored in a database table.

We want to retrieve the number of page views and then display the new number of page views- all done asynchronously, which is without the need for a page refresh.

How can this be done?

So when a user visits the page, when the page has finished downloading all elements completely, we count this as a page view.

We then get the amount of page views from the database and then display the new page views.

The following code below shows us how to do this.



So when the page has downloaded all elements, we run the ajax function.

Within this ajax function, we put a get() function, which will retrieve the number of page views that the page has received.

We specify a URL that runs a function that retrieves the number of page views the page has received.

We then take the value obtained from this retrieval and update the HTML div element that has an id attribute of 'documentviews'.

Of course, this is not the most practical example, but this is perfect for illustrating how a get() function operates in AJAX. You can create another function that gets any type of data you want and then update the page with this data using standard jQuery.

And this is how to perform an AJAX GET request in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...