POST - XMLHttpRequest in JavaScript
We can make HTTP post request using JavaScript XMLHttpRequest
object. The send() method accepts an parameter which lets you specify the post data.
Syntax
var httpReq=new XMLHttpRequest() httpReq.open('POST',url,async); var params=""; httpReq.send(params); httpReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); httpReq.onreadystatechange=function(){ if(xmlhttp.readyState === 4 && xmlhttp.status === 200){ console.log(httpReq.responseText); } }
The following example shows, how to make http post request using XMLHttpRequest object.
Example
var httpReq=new XMLHttpRequest(); var url='get_res.php'; var data='name=Tom&age=25'; httpReq.open('POST',url,true); httpReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); httpReq.send(data); httpReq.onreadystatechange=function(){ if(httpReq.readyState === 4 && httpReq.status === 200){ document.querySelector("#output").innerHTML=httpReq.responseText; } }Try it Yourself
get_res.php
<?php $name=$_POST["name"]; $age=$_POST["age"]; echo "Hello {$name}, your age is {$age}"; ?>