how-to-submit-form-data-with-jquery-ajax-in-django

How to submit data with jquery ajax in django 3

Hello World, Welcome to projectsplaza.com. Today I am going to create a tutorial on how to submit the form with jquery ajax in Django 3. This is a very simple tutorial. I will submit a form of data in the database without reloading the page in Django 3 with the help of jquery ajax. I have divided this tutorial into the following steps.

  • Setup Django with learning project and ajaxform app
  • Create a post model
  • Setup route for view
  • Create form template
  • Submit form data in the database with jquery ajax
  • Verify the submitted data

If you are new to Django then please follow this tutorial for setup python and Django.

Setup Django with learning project and ajaxform app

In this step, I will create a learning project and in this project, I will create ajaxform app.

  • Create a learning project with the following commands.
  • django-admin startproject learning
  • cd learning
  • py manage.py startapp ajaxform
  • Open learning/learning folder
  • Open setting.py and add ‘ajaxform‘ in INSTALLED_APPS list
I am using window OS so all my setup instruction according to window.

Create post model

We will save our data in SQLite database. Django comes with SQLite database. When we create model and migrate model then Django automatically create table with corresponsing fields. In this step we will create a simple post submission form. In this form, we will add title and detail ofthe post.

  • Open ajaxform/models.py
  • Add the following class in this file
from django.db import models

class Post(models.Model):
    title=models.CharField(max_length=200)
    detail=models.TextField()

    def __str__(self):
        return self.title
  • Run the following commands to create the table with fields
py manage.py makemigrations
py manage.py migrate

Setup route for view

We will access the form via URL. In this step, we will set up the route for viewing the form.

  • Open learning/urls.py.
  • Replace the following code with the existing code.
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('ajaxform.urls'))
]
  • Create learning/ajaxform/urls.py file.
  • Add the following code in the newly created file.
from django.urls import path
from . import views
urlpatterns=[
    path('',views.home,name='home'),
    path('add-data/',views.add_data,name='add_data'),
    path('view-data/',views.view_data,name='view_data'),
]

Create form template

In this step, we will create a view template for adding data with jquery ajax. We will also add the ajax code in this file.

  • Create learning/ajaxform/templates/form.html
  • Add the following code in this file.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submit Form data in database with Jquery Ajax in Django</title>
</head>
<body style="text-align: center;">
    <h3>Add Data</h3>
    <p><a href="/view-data">View Data</a></p>
    <form method="post" action="/add-data" id="formData">
        {% csrf_token %}
        <table border="1" align="center"  cellpadding="5" cellspacing="5">
            <tr>
                <th>Title</th>
                <td><input type="text" require name="title" /></td>
            </tr>
            <tr>
                <th>Detail</th>
                <td>
                    <textarea require rows="5" cols="22" name="detail"></textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <button type="button" class="save-data">Save Data</button>
                    <input type="reset" class="reset" />
                    <p class="ajax-res"></p>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Submit form data in the database with jquery ajax

In this step, we will add jquery code to submit the form data in the database. Add the following code before the close body tag.

<!-- Include Jquery -->
<script src="{% static 'jquery-3.4.1.min.js' %}"></script>
<script>
    $(document).ready(function(){
        $(".save-data").on('click',function(){
            var fd=$("#formData").serializeArray();
            var vm=$(this);
            // Ajax
            $.ajax({
                url:"add-data/",
                type:'POST',
                data:fd,
                dataType:'json',
                beforeSend:function(){
                    vm.text('Saving...')
                },
                success:function(res){
                    if(res.bool==true){
                        $(".ajax-res").text('Data has been added');
                        $(".reset").trigger('click');
                    }else{
                        $(".ajax-res").text('Data has not been added');
                    }
                    vm.text('Save Data');
                }
            });
        });
    });
</script>

Create a Django function to add data in the database

In this step, we will add functionality in Django to add the form data in the database. When you access the URL and submit the form then this functionality gets all data with the post method and adds data in the database then sends the response to the browser.

  • Open the learning/ajaxform/views.py
  • Add the following code in this file
from django.shortcuts import render
from django.http import JsonResponse
from .models import Post
def home(request):
    return render(request,'form.html')

def add_data(request):
    if request.method=='POST':
        title=request.POST['title']
        detail=request.POST['detail']
        inst=Post.objects.create(title=title,detail=detail)
        data=None
        if inst:
            data={
                'bool':True
            }
        else:
            data={
                'bool':False
            }
        return JsonResponse(data)

def view_data(request):
    posts=Post.objects.all()
    return render(request,'data.html',{'posts':posts})

Create a Django function to view data

In this step, we will fetch all data from the database and show it.

  • Create data.html in the templates folder and add the following code.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Data</title>
</head>
<body style="text-align: center;">
    <h3>All Data</h3>
    <p><a href="/">Add Data</a></p>
    <table border="1" align="center"  cellpadding="5" cellspacing="5">
        <tr>
            <th>Title</th>
            <th>Detail</th>
        </tr>
        {% for post in posts %}
        <tr>
            <td>{{post.title}}</td>
            <td>{{post.detail}}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>
  • We have already added the code for view data in views.py’ file.

  • Run this command to run server py manage.py runserver
  • Open http://127.0.0.1:8000 for add data
  • Open http://127.0.0.1:8000/add-data/

 

Leave a Reply

Your email address will not be published. Required fields are marked *