Send POST data using XMLHttpRequest

Jack Greenhill picture Jack Greenhill · Mar 15, 2012 · Viewed 1.2M times · Source

I'd like to send some data using an XMLHttpRequest in JavaScript.

Say I have the following form in HTML:

<form name="inputform" action="somewhere" method="post">
  <input type="hidden" value="person" name="user">
  <input type="hidden" value="password" name="pwd">
  <input type="hidden" value="place" name="organization">
  <input type="hidden" value="key" name="requiredkey">
</form>

How can I write the equivalent using an XMLHttpRequest in JavaScript?

Answer

Ed Heal picture Ed Heal · Mar 15, 2012

The code below demonstrates on how to do this.

var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

In case you have/create an object you can turn it into params using the following code, i.e:

var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;

// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
 urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}