AJAX - POST Method

by Devansh

Posted on 18 Mar 2018 04:03:15 (2 years ago)

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 open the connection. After that we need to set the header path and then again we will check the ready state and wait for response. Then, in last we will send the request. Below, is the required code for AJAX POST request.

var theObject = new XMLHttpRequest();
theObject.open("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){

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'];