Submit form using javascript and ajax without page refresh. Disable the page reload and submit the form using Form data HTML5 API.
The following example demonstrates an HTML5 form submiting data via an Ajax API call using the POST
method. The ajax call will be processed by an REST resource written in xml.
The HTML5 Form API provides a number of javascript APIs to avoid direct manipulation of individual input elements.
When the end-user inputs the data in the form and clicks the submit button the form data is sent with the HTTP POST method, this data onsubmit function catches the data and with the help of the xhr.send
request sends the data to the respective URL.
<form id="login-form">
<div class="form-group">
<label for="xuser">Username</label>
<input type="text" name="iuser" class="form-control" />
</div>
<div class="form-group">
<label for="xpass">Password</label>
<input type="password" name="xpass" class="form-control" />
</div>
<input type="hidden" name="redirect" value="home-page" />
<input type="submit" class="btn btn-danger" value="Submit" class="form-control" />
</form>
input
elements should be inside the form
tag.action="/tests/v1.0/form"
or method="POST"
<input type="submit" />
The form can be decorated with CSS and this does not affect the functionality. The javascript API will not work if above things are not kept in the form.
All the input fields including hidden fields will be sent on the server without any extra javascript. This is thanks to the FormData API.
Pass the form object to FormData constructor to populate the form object.
The FormData object contains all the fields as name
attribute of input fields <input name="iuser" />
, Using the FormData.get() API, each form value can be fetched.
//get the form from DOM (Document object model)
var form = document.getElementById('login-form');
form.onsubmit = function(event){
var xhr = new XMLHttpRequest();
var data = new FormData(form);
//Add extra data to form before submission.
data.append("referer","https://example.com");
//open the request
xhr.open('POST','http://localhost:7000/tests/v1.0/form')
//send the form data
xhr.send(data);
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
form.reset(); //reset form after AJAX success.
}
}
//Dont submit the form.
return false;
}
If additional parameters needs to be send in the form, they can be appended to the FormData object.
Dont forget the last line. The onsubmit function should always return false,indicating to HTML5 Form API that form should not be submitted.
FormData object holds key-value pairs, as we can see in the above example.We need to conver these key-value pairs into an object.
The Object.fromEntries() method transforms a list of key-value pairs into an object.
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var json = JSON.stringify(Object.fromEntries(formData));
xhr.send(json);
We cannot directly send the object over the network. Object needs to be converted into a json string and sent using xhr.send
method.
It is important to let the server know, we are sending the data in json format using the Content-Type
header.
After submit operation, we can wait for the respone and reset the form once success response is recieved. We can do other operations like
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
form.reset(); //reset form after AJAX success.
}
}
Fetch is a browser APIs which allows sending HTTP requests. In the below example we have replaced XHR with fetch.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then();
//Dont submit the form.
return false;
}
The form-data format for sending data over the network to the server.
The parameters sent in the POST request are received on the server. The parameters on the server can be accessed using name attribute value given in the form.
To understand how POST request works in ajax call, checkout GET vs POST in REST API.