In this tutorial i am going to change a simple html form into Ajax form or submitting a form without reload. For this purpose i will use jQuery Ajax method and serialize method.
i also created simple jQuery plugin which you can integrate in your web application and take benefit of it. so let’s begin with some simple steps.
Step 1: Create a html form
First step is to create a html form
<div class="col-md-6 offset-md-3">
<h3>Convert any form into Ajax form - Readerstacks.com</h3>
<form method="post" id="validateajax" action="submit.php" name="registerform">
<div class="form-group">
<label>Email</label>
<input type="text" name="email" value="" class="form-control" />
</div>
<div class="form-group">
<label>Phone number</label>
<input type="text" name="phone_number" value="" class="form-control" />
</div>
<div class="form-group">
<label>Picture</label>
<input type="file" name="picture[]" class="form-control" />
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" value="" class="form-control" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</form>
</div>
Step 2: Add jQuery and handle form submit
Next step is to include the jQuery library in page and handle the form submission.
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
Now, implement the jquery
$(function(){
$("#validateajax").on("submit",function(e){
e.preventDefault();
var action = $(this).attr("action");
var method = $(this).attr("method");
var form_data = new FormData($(this)[0]);
$.ajax(
{
url: action,
dataType:'json', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: method,
success: function (response) {
// display success response from the server
},
error: function (response) {
},
})
});
});
Here, we add handled submit event and then find the form action and method. In the next line, we converted the form object in FormData.
Step 3: Check the implement
Download or check live implementation