django + ajax
Photo by Austin on Unsplash

using ajax with django with some cool examples

sriram
sriram
June 22

At the end of this post you would know to 

  1. Submit form using ajax without page refresh
  2. Send data to server through GET or POST method
  3.  get csrf token value using django templates and jquery

If you like dark mode switch to full screen. Without further delay let's get started 😃😉😃.

I have created a simple project named djangoajax with a simple app named authentication which handles login and sign up.

project structure
project structure

First we will quicly look through how to send some data to django views to a specific URL later we will see about form submission.

Before starting I assume that

Creating urls to send the data

In the root URL i.e urls.py file where the settings.py file is located, I have pointed the URL auth/ to authentication app so we can work on different urls from authentication category.

Now let's create an URL in urls.py file in authentication app which we will use to receive a sample data that will be sent through AJAX from client side. 

The get_data is the function which we will create shortly. So basically what we are doing is when someone calls for the URL /auth/post-data/ , get_data function will be called. This is a simple example we will see complex example later in this post. 

Creating function in views to receive data sent though ajax 

Receiving data from ajax is not different from getting data from a normal GET or POST or PUT etc.., Think this way django doesn't know how the data is sent, it only knows what the data contains and to which URL it's sent or requested. By the way AJAX short for Asynchronous JavaScript and XML used  to create asynchronous web applications. asynchronous just means that you don't need to reload the page or wait until the process is finished it will go on in the background. For example, when a user click submit a loading animation is displayed to the user whereas in background data is sent to the server and the client is waiting for the response. Simple isn't it? We will discuss more about this when we are creating javascript code. For now remember django interprets ajax requests as normal http request. in the code below data is sent through POST method which we receive using request.POST 

This request object belongs to  class HttpRequest contains number of data like COOKIES, FILES, META, headers and more see here. reuqest.POST is a dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data see here.

JsonResponse which we return is a HttpResponse subclass that helps to create a JSON-encoded response. json short for JavaScript Object Notation is a lightweight format for storing and transporting data across the web. Here JsonResponse function takes a dictionary as a parameter which django serializes to json data which really makes task easier. 

Other parameters

JsonResponse(data, encoder=DjangoJSONEncoder, 

safe=True, json_dumps_params=None, **kwargs)  

Creating an ajax call using jQuery

Below these are simple steps to create an ajax request using jQuery

  1. Load jQuery either through CDN or from server
  2. Call ajax function using jQuery's ajax method $.ajax()
  3. Pass the required parameters as a dictionary. In our case it's URL, data, and HTTP method is POST 

I have created a simple HTML that will send the data when a button is clicked

By now you will be like 

Talk is cheap show me code meme
Talk is cheap show me code meme

ok ok I will show the code then talk.

html and javascript code to make an ajax call

So when the button is clicked the postData function is called inside the function an ajax call is made to the

URL : auth/post-data

METHOD : POST

The success function is called when the response is success in our case we are returning JsonResponse that is success (200). If the server returns an error for example 404( not found ) or 500 ( server error ) then the error function will be called. 

{% csrf_token %}is used to protect from cross site request forgery.

Cross-site request forgery  is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform. know more about csrf attack here. Know how django helps protect from csrf attack here. csrf_token tag sets the csrf value in an input field with type hidden example: <input type="hidden" name="csrfmiddlewaretoken" value="hMBEZHfo7JcVPoif0JrVs0C2">

. To get csrf token value use getCookie('csrftoken') or by using javaScript Cookie library.

const csrftoken = Cookies.get('csrftoken');

In this post I used jQuery to get the value. Please note the variable name to send the csrf cookie value should be csrfmiddlewaretoken. django uses this value to check against the value saved in the database. Let's try the code 😏. Oops we did not write code to return the html  page. We shall use the same function, if request method is get the html template will be returned else it can assume that the method is post. there are other methods also like PUT, DELETE, CONNECT and more.

That's it, test the code 🧐. it's working for me in the first run. Rare case 😅.

Tell your views in the comment section. That's it you've learnt to create an asynchronous request let's work with this to submit a sign up form. 

***

Examples and use cases of ajax call

Now I will show you a very good example where ajax is used after this example I will show you how to create infinite scrolling like instagram using ajax call cool right ?😎 skip to that example if you want. This example I will use ajax to submit sign up post form. 

Submitting form with ajax

First let's create a simple form which takes username, password and email.

External links


Today's deal from platiplus

More from the author

django + ajax

using ajax with django with some cool examples

Comments (0)

Add a Comment

Reply