Home » AJAX

Sending post request method with the AJAX request



In this article, we are going to learn how to send AJAX request via POST method? This article contains the code to send request via POST method and explanation on that.
Submitted by Abhishek Pathak, on October 09, 2017

AJAX is an emerging web technology that is shaping the modern web. With the introduction of AJAX, we have witnessed the development of web applications that provide user experience like native application. Therefore, having AJAX in your skill set is important as per today's standards. We have a list of articles on the AJAX topic if you would like to visit.

Post method is a secure method of transferring data to the server as details are not exposed.

Suppose you want to send some confidential data like passwords, it is important to use post method as it encrypts the data and send it to server.

Here is a code that explains how to send AJAX request via POST method.

Code:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(this.readyState === 4 && this.status === 200)
    alert(this.responseText);
}
xhr.open('POST', '/submit-data.php', true);
xhr.send();

First, we create a xhr variable that is the object of the xmlHttpRequest. Then we define the onreadystatechange() to execute the function when the data from server is sent back. Now, whenever there is any change it executes this code. The this.readyState property checks if the state is 4, which is the response has been received from server and also if this.status is equal to 200, it will alert the reponseText receive from the server.

Here, we were sending the xmlHttpRequest object via POST method, as it is seen in the first parameter of xhr.open() function. Now, the data will be transferred to submit-data.php which is our file hosted on server and processing of the request will be done here.

This is how you send data via POST method in AJAX? Share your thoughts in the comments below.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.
Close