in this article, I will show you the best method to post data with Django and jquery ajax.
Firstly, we need to write an HTML form.

Code:


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

In view.py we will write a 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 input first_name id
        last_name = request.POST.get('last_name', None)  # getting data from input last_name id
        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 will make URL for our function
Code:


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, its time to write a jquery function that sends data and gets a response
Code:


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

e.preventDefault();

  $.ajax({
       type : "POST", 
       url: "{% url 'ajax_posting' %}", /* django ajax posting url  */
       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() {
           
       }


   });


        });     

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