AJAX Post request example
Posted on: October 19, 2021 by Deven
There are various HTTP methods available to access data or send data to the server. HTTP provides get, post, put, patch, delete methods. In today’s post we are going to use Post method with the help of AJAX.
AJAX stands for Asynchronous JavaScript And XML, which allows the webpage to be updated in the backgroud without refreshing the page. Using AJAX you can either request, receive or send the data to server. Its a general convention to use the POST method to send the data to server & server creates new resources received in the request body.
example:
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Request completed");
}
};
xhttp.open("POST", "create_account", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("firstName=John&lastName=Doe");
AJAX call using jQuery:
$.ajax({
url: '/create_account',
type: 'POST',
data: {
email: "test@example.com",
phoneNo: "7777777777",
country: "+91",
firstName: "John",
lastName: "Doe",
},
dataType: 'json',
success: function (msg) {
console.log(msg);
},
error: function (jqXHR, textStatus) {
let responseText = jQuery.parseJSON(jqXHR.responseText);
console.log(responseText);
}
});
Share on social media
//