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 will write a simple function that gets data from the form and return a response as JSON.

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


#index.html

<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>



$('#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() {
           
       }


   });


        });     

"{% url 'ajax_posting' %}": name of url that we set for 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

English today is not an art to be mastered it's just a tool to use to get a result