Home Django How to work with AJAX Request in Django

How to work with AJAX Request in Django

AJAX is an acronym for Asynchronous JavaScript And XML. AJAX technologies allow web pages to update asynchronously by exchanging data to and from the webserver. In essence, the web page can be updated without reloading the entire web page. It utilizes XMLHttpRequest objects to transmit and receive data.

How AJAX works

  • When an event such as form submission, page load, or when a button is clicked on a web page occurs, an XMLHttpRequest object is created and sends the request to the server.
  • The server will respond to the request.
  • The requested response is captured, and the webserver responds with the requested response data.

AJAX is useful in scenarios when you want to make GET and POST requests to load data from the server asynchronously. It enables web applications to be more dynamic and reduces page load times.

How Ajax works in Django

how ajax works in django
How ajax works in Django

AJAX concept in Django

1- Javascript Code on the Browser/client-side

A browser makes a request when an event occurs on the web page. The JavaScript code generates an XHR object which contains JavaScript object or data and is sent as a request object to the webserver. The XHR object will essentially name the callback function on the server or URL.

2- The request is handled by the webserver

When the request has been sent, the appropriate callback function handles the request, and it will send a success or failure response. Due to the request’s asynchronous nature, the code will execute without interruptions, and the server processes the request.

3- Success or failure response

A successful response will contain data in multiple formats like text, JSON, XML

Real-World Example

AJAX has very many applications on web pages and applications. An example is a like button on Facebook or Linkedln. When a post is liked, several actions are performed both in the back-end and front-end. For example, the like button’s color might change, or the number of likes on the post will be incremented in the database.

The process is simplified as follows:

When the like button is clicked, an XHR object is sent to the server, the server receives the request and performs the action created for the request. In this case, it registers the like for the post. The server then sends a success response, and the Like button changes color or the number of likes is incremented, or both.

A look at Django

Django has been described as the web framework for perfectionists with deadlines and is a prevalent Python web framework. Django can be characterized as an MVC (Model View Controller) and MTV (Model Template View). The model class ties into an ORM where instances correspond to rows in the table. The template is a system designed for ease of use and limits the extent to which HTML is used throughout the Python source code. The view is a function that renders from a template.

Using jQuery for AJAX in Django

jQuery is one of the most popular JavaScript libraries that has been utilized to develop other JavaScript frameworks like React or Angular. It provides functions with DOM of web pages.

Why Use jQuery

AJAX has a different implementation on multiple browsers

Different browsers use various XHR APIs that parses the request and respond slightly differently. jQuery provides you with a built-in solution to keep your code up-to-date while making it platform-independent. Jquery code is actively developed and thus is kept updated.

jQuery provides various methods of using DOM

jQuery contains many DOM objects and related methods. These objects can be used depending on the developer’s needs, and jQuery makes it more convenient to use.

jQuery is the basis for many popular frameworks

Many popular frameworks like React Js, Angular Js are based on jQuery. jQuery is virtually everywhere on popular JavaScript frameworks.

jQuery is very popular

jQuery is a viral library among web developers with many IT industry features. Javascript frameworks provide ready-made widgets, and frameworks can let you write higher-level JavaScript and a little more Pythonic.

There are other ways to use AJAX in Django, but these reasons make jQuery a popular choice. Therefore we will use it to demonstrate how to work with requests in Django.

User Registration Scenario

As a web developer, you want to validate the username field in the registration or sign-up view as soon as the user finishes typing the username. The check you want to perform is simple if the username is already taken or not.

Initial Setup

After the initial setup for Django, create a project and create the base.html file.

base.html

{% load static %}<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{% block title %}Default Title{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/app.css' %}">
    {% block stylesheet %}{% endblock %}
  </head>
  <body>
    <header>
      ...
    </header>
    <main>
      {% block content %}
      {% endblock %}
    </main>
    <footer>
      ...
    </footer>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script src="{% static 'js/app.js' %}"></script>
    {% block javascript %}{% endblock %}
  </body>
</html>
Note that the jQuery library and the JavaScript resources should be placed at the end of the HTML page to guarantee the DOM will be loaded when the script is executed and to avoid inline scripts that use jQuery.

views.py

from django.contrib.auth.forms import UserCreationForm
from django.views.generic.edit import CreateView

class SignUpView(CreateView):
	template_name = 'core/signup.html'
	form_class = UserCreationForm

url.py

from django.conf.urls import url
from core import views

urlpatterns = [
>path(' signup/', views.SignUpView.as_view(), name='signup')
]

signup.html

{% extends 'base.html' %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

AJAX Request Implementation

The AJAX implementation below is an asynchronous request to validate if the user’s input for username is already taken or is available for use. The first step involves looking at the HTML generated by {{form.as_p}} to inspect the username field below:

To validate the username, we create a listener for the id_username filed change event.

signup.html

{% extends 'base.html' %}

{% block javascript %}

  <script>
    $("#id_username").change(function () {
      console.log( $(this).val() );
    });
  </script>

{% endblock %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

In the implementation above the change, the event will occur every time the value of the username field changes. Next, we create a view that checks if a given username is taken and returns a JSON response.

views.py

from django.contrib.auth.models import User
from django.http import JsonResponse

def validate_username (request):
    username = request.GET.get('username', None)
    data = {
        'is_taken': User.objects.filter(username__iexact=username).exists()
    }
    return JsonResponse(data)

The next step is to add a route to the view(views.py).

urls.py

from django.conf.urls import url
from core import views

urlpatterns = [
path(' signup/', views.SignUpView.as_view(), name='signup'),
path(' ajax/validate_username/', , views.validate_username, name='validate_username'),
]

Finally, we implement the AJAX as below.

Signup.html

{% extends 'base.html' %}

{% block javascript %}

  <script>
    $("#id_username").change(function () {
      var username = $(this).val();

      $.ajax({
        url: '/ajax/validate_username/',
        data: {
          'username': username
        },

        dataType: 'json',
        success: function (data) {
          if (data.is_taken) {
            alert("A user with this username already exists.");
          }
        }
      });

    });
  </script>

{% endblock %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

The code above has added an event to handle the user input, which then calls a function that uses AJAX to check if a given username is taken and returns a response.

Best practices for AJAX JavaScript in Django

-Avoid modifying JavaScript code with Python code.
-Keep the URL references in the HTML and manage user messages in the Python Code
-On the HTML field, prefer to add a class name.

Once you have added the class name, you can hook the change event to the class js-validate-username. The prefix js in the class name suggests a JavaScript code that interacts with this element.

Forms are at risk of Cross-Site Request Forgeries(CSRF) attacks. To prevent CSRF attacks, add the {% csrf_token %} template tag to the form. It will add a hidden input field containing a token sent with each POST request.

Conclusion

Ajax is a bit interdisciplinary; it involves server-side technologies like Django, client-side scripting, and libraries, including jQuery, CSS, HTML, and the DOM.

Ajax is fascinating because it opens doors in the user interface, usability, and user experience; excelling with Ajax is just as technical as it is like arts and humanities.

Finally, we have to keep in mind that jQuery is JavaScript. It is a JavaScript library used to reduce the code you need to write.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More