[Answered ]-How to integrate Django form with Ajax?

2👍

Example of Ajax Post
on button click submit

this method needs to run

put this in your HTML

function AddData(){
    var name = $("#name").val();
    var email = $("#email").val();

    // You should extract each and every id from your form fields


    var signupData = { name:name, csrfmiddlewaretoken: '{{ csrf_token }}',email:email};
    $.ajax({
                type: "POST",
                url: "../../index/",
                data: signupData,
                success: function(data) {
                                        alert("You Have Sucessfully Signed Up ");

                                                                    },
                                        statusCode: {
                                                      500: function() { 
                                                                        alert("You Have Already Signed Up ");
                                                                       }
                                                      },
                                    })
    }

In your Views.py

def index(request): 
    if request.method == 'POST': # From Frontend we are getting the data in a POST method and we are checking if front end is giving POST Method or not 
        get_email = request.POST.get('email') # Taking The DATA from front end in form of POST to Django  USER EMAIL ADDRESS
        get_name = request.POST.get('name')# Taking The DATA from front end in form of POST to Django NAME
        queryset_list = SignUp.objects.all().values_list("email",flat=True)# Performing a Django Query and getting all Signup Email Address
        if get_email in queryset_list:
           return HttpResponse(status=500)
        else:
           SignUp.objects.create(name=get_name,email=get_email)
    return HttpResponse('')

Leave a comment