Last modified: May 07, 2021

How to Submit a Form With Django and Ajax

in this article, I will show you how to post a form with Django and jquery ajax.

views.py

In view.py we'll write two functions:
index function: display our HTML form.
ajax_posting function: handle the form by getting data and send a response.

Code:


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


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


# ajax_posting function
def ajax_posting(request):
    if request.is_ajax():
        first_name = request.POST.get('first_name', None) # getting data from first_name input 
        last_name = request.POST.get('last_name', None)  # getting data from last_name input
        if first_name and last_name: #cheking if first_name and last_name have value
            response = {
                         'msg':'Your form has been submitted successfully' # response message
            }
            return JsonResponse(response) # return response as JSON

and in url.py we'll add URLS for our functions.

urls.py


from django.contrib import admin
from django.urls import path
from core.views import *
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index), # index url
    path('ajax-posting/', ajax_posting, name='ajax_posting'),# ajax-posting / name = that we will use in ajax url
]


Now, let's create index.html in our Django Templates Folder and write a jquery function that sends data and gets a response

index.html



<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
   </head>
   <body>
      <form id="form" method="POST">
         <input id="first_name" type="text" name="title">
         <input id="last_name" type="text" name="lang">
         <input  type="submit" name="submit" value="submit">
      </form>
      <div id="output">
      </div>
      <script>
         $('#form').on('submit', function(e){
             
         e.preventDefault();
         
           $.ajax({
                type : "POST", 
                url: "{% url 'ajax_posting' %}",
                data: {
                 first_name : $('#first_name').val(),
                 last_name : $('#last_name').val(),
                 csrfmiddlewaretoken: '{{ csrf_token }}',
                 dataType: "json",
         
                },
                
                success: function(data){
                   $('#output').html(data.msg) /* response message */
                },
         
                failure: function() {
                    
                }
         
         
            });
         
         
                 });    
      </script>
   </body>
</html>



"{% url 'ajax_posting' %}": name of url that we have set for the ajax_posting function.

now let's test our form

befor submiting:

How to submit a form with django and ajax

after submiting:

How to submit a form with django and ajax