In this tutorial we will be using jQuery to submit AJAX forms. Let’s see how.
1. Create the frontend
We will create the frontend using HTML. In the following piece of code we are creating a simple form. We created two input fileds. The first input field takes in the user name and the second input field requires the email address of the user.
We have included the id values to each input field because jQuery script uses these to process the form.
<html>
<head>
<title>How to Submit AJAX Forms using jQuery</title>
<script src="<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js</a>" />
</head>
<body>
<div class="form">
<h1>AJAX Form</h1>
<form action= "process.php" method= "POST">
<input type= "text" id= "name" name= "name" placeholder="Full Name" />
<input type= "text" id= "email" name= "email" placeholder="email" />
<button type= "submit" class= "btn">Submit Form</button>
</form>
</div>
</body>
</html>
2. Adding jQuery logic
Now we will use jQuery logic. Without jQuery sending AJAX requests can be a bit tricky but with jQuery the task becomes a little bit easy. With jQuery AJAX methods you can easily load your data from the selected HTML elements of your web page.
The following code extracts data from the input fields which are name and email. Afterwards an AJAX request is made and the response is displayed.
$("form").submit(function (event) {
varformData = {
name: $("#name").val(),
email: $("#email").val(),
};
$.ajax({
type:"POST",
url: "process.php"
Data: formData,
dataType: "json"
encode: true,
}).done(function (data) {
console.log(data);
})
Conclusion
Forms are a crucial part of a website and AJAX allows a user to refresh a part of a page without going through the difficulty of refreshing the entire document. An AJAX form is capable of sending and receiving information in different formats like, HTML, JSON or XML. This tutorial gives the reader a step-by-step guidance to creating and submitting an AJAX form using jQuery.