Now, we have seen how to use the GET method. Now, Its time to use POST method. In POST method we have to do few steps more as compared to GET method.

We will start with instantiating the object of "XMLHttpRequest". Same as GET method. Then, we will use open() and send() function to send the request to the server.

var theObject = new XMLHttpRequest();"POST", "data-file-path.php", true);

Now we will use one more method of the XMLHttpRequest i.e. setRequestHeader(). In this method you need to setup all your HTTP headers. A simple e.g. is below,

theObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Then again we will check the ready state and wait for response. Then, in last we will send the request. Below, is the full sample code for AJAX POST request.

var theObject = new XMLHttpRequest();"POST", "data-file-path.php", true); //e.g. data-file-path.php -> js.php, file.php, etc.
theObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
theObject.onreadystatechange = function(){
	if(theObject.readyState == 4 && theObject.status == 200){

Here, I want to mention one thing more that in send() method you need to specify the data you want to send.

Now in "data-file-path.php" we have data in POST method and now we can do anything we want. Below is the example of POST data handling.

if (isset($_POST)) {
     echo $_POST['username'] . " " . $_POST['password'];

Last Modified: 2 years ago