Working with AJAX request and Django
Tags: django, javascript
Published: 2020-12-27 18:03:32

Hey there! There are a lot of scenarios where we want to use AJAX requests in web applications. It helps web applications to be much faster and dynamic. In this post, we will explore how we can handle AJAX requests in Django and we will be using function-based views and jQuery for simplicity. Without wasting any time, let's jump to the interesting part.

#### **Initial set-up**
Here is my base.html file. The jQuery library is added at the end of this page.
```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
    {% block content %}
    {% endblock %}
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script src="{% static 'js/app.js' %}"></script>
</body>
</html>
```

#### **Sample**
For this tutorial, let's assume we want to validate the **username** field as soon as the user enters his username. We will do a simple check to see whether the username exists or not.

##### urls.py
```
from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name="index"),
]
```

##### views.py
```
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request,'register.html')
```

##### register.html
```
{% extends 'base.html' %}

{% block content %}
<div class="col-lg-4">
<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" class="form-control mb-3" id="username" placeholder="Username">
    <input type="password" class="form-control mb-3" placeholder="Password">
    <input type="password" class="form-control mb-3" placeholder="Repeat Password">
    <input type="button" value="Submit" class="btn btn-primary">
</form>
</div>
{% endblock %}
```

#### And this is how the view looks.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rfj1irdilw8wixwg00j6.PNG)


#### **AJAX Request**
Let's implement an AJAX request to check whether the username is already taken or not. We need the id of the username field and we will add a listener on its change event.

##### app.js
Here the change event occurs every time the value of the username field changes. Make sure the event is getting fired correctly and you got the listener right. The AJAX request uses the POST method here (you can use any according to your need).
```
$("#username").change(function () {
        var username = $(this).val();
        $.ajaxSetup({
            headers: {
                "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,
            }
        });
        $.ajax({
        url: 'validate',
        method: 'POST',
        data: {
          'username': username
        },
        dataType: 'json',
        success: function (data) {
          if (data.taken) {
            alert("Username taken");
          }
        }
      });
    });
```

##### views.py
```
from django.contrib.auth.models import User

def validate(request):
    username = request.POST['username']
    data = {
        'taken' : User.objects.filter(username__iexact=username).exists()
    }
    return JsonResponse(data)
```

#### Add a route for this view.

##### urls.py
```
from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name="index"),
    path('validate',views.validate,name="validate"),
]
```

#### And here's the output.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u1pokyybnr74wlpecpui.PNG)

  
That was it. Now, you have learned to handle AJAX requests in Django. You can also do this using plain JavaScript, just the app.js would be slightly different. Thank you for your precious time.

Adios!