AJAX is a developer's dream, because you can:

  • Update a web page without reloading the page
  • AJAX = Asynchronous JavaScript And XML.
  • AJAX is not a programming language.
  • AJAX just uses a combination of:
    • A browser built-in XMLHttpRequest object (to request data from a web server)
    • JavaScript and HTML DOM (to display or use the data)

Rerunning the Student Registration program.

  • We are going to rerun the Student Registration program and compare it's output after implementing AJAX to it.
  • Go to program list and select Student Registration program in this webpage and follow the instructions and execute it.
  • Follow the instructions and get the program running. Or you can Download projectand alter it.
  • Defaul Username and password is "user"

Notice the difference

  • After updating some course in the admin panel, come back to registration page.
  • Try to add new students to the course. Notice anything ?, yeah each time we register new student page get's reloaded to update the data in database.
  • We are going to do this registration without reloading the page using AJAX.

Make the changes in register.html and views.py file.

  • Update register.html
<!DOCTYPE html>
<head>
    <title>Register Student to Course</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h2>Register Student</h2>
    <form id="registrationForm" method="post" action="{% url 'register' %}">
        {% csrf_token %}
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" maxlength="50" required>
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br>
        <label for="course">Select Course:</label>
        <select id="course" name="course" required>
            {% for course in courses %}
                <option value="{{ course.id }}">{{ course.title }}</option>
            {% endfor %}
        </select>
        <br>
        <button type="submit">Register</button>
    </form>
    <div id="message"></div>

    <!-- Let the students view who all opted for particular course by selecting the course -->
    <form id="redirectForm" method="get" onsubmit="redirectToRegisteredStudents(event)">
        <label for="course_title">Enter Course Title:</label>
        <input type="text" id="course_title" name="course_title" required>
        <button type="submit">Go</button>
    </form>

    <script>
        function redirectToRegisteredStudents(event) {
            event.preventDefault(); // Prevent the default form submission
            var courseTitle = document.getElementById('course_title').value;
            if (courseTitle) {
                // Encode the course title to be URL safe
                var encodedCourseTitle = encodeURIComponent(courseTitle);
                // Redirect to the desired URL
                window.location.href = '/registered/' + encodedCourseTitle + '/';
            }
        }

        $(document).ready(function(){
            $('#registrationForm').on('submit', function(event){
                event.preventDefault();
                $.ajax({
                    type: 'POST',
                    url: '{% url "register" %}',
                    data: {
                        name: $('#name').val(),
                        email: $('#email').val(),
                        course: $('#course').val(),
                        csrfmiddlewaretoken: '{{ csrf_token }}'
                    },
                    success: function(response){
                        $('#message').html('<p>' + response.message + '</p>');
                        $('#registrationForm')[0].reset();
                    },
                    error: function(response){
                        $('#message').html('<p>An error occurred</p>');
                    }
                });
            });
        });
    </script>
</body>
</html>
  • Update view.py file.
from django.shortcuts import render, redirect, HttpResponse, get_object_or_404
from django.contrib import messages
from django.http import JsonResponse
from .models import Student, Course

def test(request):
    return HttpResponse("this is a test")

def register(request):
    if request.method == 'POST':
        student_name = request.POST['name']
        student_email = request.POST['email']
        course_id = request.POST['course']
        course = Course.objects.get(pk=course_id)
        student, created = Student.objects.get_or_create(name=student_name, email=student_email)
        course.students.add(student)
        return JsonResponse({'message': 'Student successfully added to the course.'})
    else:
        courses = Course.objects.all()
        return render(request, 'register.html', {'courses': courses})

def registered(request, course_title):
    course = get_object_or_404(Course, title=course_title)
    students = course.students.all()
    return render(request, 'registered.html', {'course': course, 'students': students})

Now you'll see the Difference

  • Save the changes rerun the local server and now try to register. No need of making migrations, cause we didn't touched the database.
  • Run the local server and go to this url http://localhost:8000/register/
  • Now try to register. Noticed the difference? The page will not load when we try register, like it used to do without AJAX.
  • If you see in your local server running terminal you'll see "HTTP POST parameters that are sent to your view without loading the page"

Resourses

  • w3schools
  • jQuery.ajax() | jQuery API Documentation

Watch a quick video summary on how to run this program

Watch it at 2x speed