DEV Community

Cover image for Ajax & Django - Rid of Page Reloading
Madhuban Khatri
Madhuban Khatri

Posted on

Ajax & Django - Rid of Page Reloading

Hello Developers,
In this post, I am discussing about Ajax use in Django because it is important for page reloading.

Ajax is stand for Asynchronous Javascript and XML

For example, If a developer is working on Social Media Project and in this project he/she can do a lot of things (Follow/Unfollow other users and Like the user posts). These tasks can be done without Ajax but with Page Reloading. So we use Ajax for this(No Page Reloading).

Alt Text

Here is the example of a Simple Ajax and Django Project:-

app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('add_user/', views.add_user, name='add_user'),
]
Enter fullscreen mode Exit fullscreen mode

app/views.py

from django.shortcuts import render
from django.http import JsonResponse
from .models import User

# Create your views here.
def index(request):
    users = User.objects.all()
    param = {'users': users}
    return render(request, 'index.html', param)


# Important part
def add_user(request):
    if request.method == 'GET':
        firstName = request.GET['fname']
        lastName = request.GET['lname']

        add_user = User(first_name=firstName, last_name=lastName)
        add_user.save()

    return JsonResponse({'user_id':add_user.id, 'first_name': add_user.first_name, 'last_name': add_user.last_name})

Enter fullscreen mode Exit fullscreen mode

templates/index.html

<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  <title>Ajax and Django</title>
</head>
<body class="bg-danger text-warning">
  <div class="container">
    <div class="row">
      <div class="col-4">
        <h1>Use Ajax in Django</h1>
        <hr>
        <form id='my_form'>
          <input type="text" id="f_name" class="form-control" placeholder="First Name">
          <br>
          <input type="text" id="l_name" class="form-control" placeholder="Last Name">
          <br>
          <input type="submit" id="add_btn" value="Add User" class="btn btn-primary">
        </form>
      </div>

      <div class="col-8">
        <h1>Use Ajax in Django</h1>
        <div>
          <table class="table text-light">
            <thead>
              <tr>
                <th scope="col">Id</th>
                <th scope="col">First Name</th>
                <th scope="col">Last Name</th>
              </tr>
            </thead>
            <tbody id="table_data">
              {% for user in users %}
              <tr>
                <th scope="row">{{user.id}}</th>
                <td>{{user.first_name}}</td>
                <td>{{user.last_name}}</td>
              </tr>
              {% endfor %}

            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Option 1: Bootstrap Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>


  <script type="text/javascript">
  // Important Part
  var btn = $('#add_btn');
  btn.on('click', function(e){
    e.preventDefault();
    var first_name = $('#f_name').val();
    var last_name = $('#l_name').val();
    var card_contain = $('#card_contain');

        // Ajax Call
        $.ajax({
          type: 'GET',
          url: '{% url "add_user" %}',
          data: {fname: first_name, lname: last_name},
          dataType: 'json',
          success: function(response){
            var tableData = $('#table_data');
            var table_row = '<tr>';
            table_row += '<th scope="row">'+response.user_id+'</th>';
            table_row += '<td>'+response.first_name+'</td>';
            table_row += '<td>'+response.last_name+'</td></tr>';
            tableData.append(html);
            $('#my_form').trigger('reset');
          }
        });
      });

  </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Do you understand how to use Ajax in Django and what is the use of Ajax?

Here is my another post:-

Top comments (0)