Last modified: November 14, 2020

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.

In we will write a simple function that gets data from the form and return a response as JSON.


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 we'll add URLS for our functions.

from django.contrib import admin
from django.urls import path
from core.views import *
urlpatterns = [
    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



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

<div id="output">


$('#form').on('submit', function(e){


       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