Send POST data using XMLHttpRequest Send POST data using XMLHttpRequest ajax ajax

Send POST data using XMLHttpRequest


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 requesthttp.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]));}


var xhr = new XMLHttpRequest();xhr.open('POST', 'somewhere', true);xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');xhr.onload = function () {    // do something to response    console.log(this.responseText);};xhr.send('user=person&pwd=password&organization=place&requiredkey=key');

Or if you can count on browser support you could use FormData:

var data = new FormData();data.append('user', 'person');data.append('pwd', 'password');data.append('organization', 'place');data.append('requiredkey', 'key');var xhr = new XMLHttpRequest();xhr.open('POST', 'somewhere', true);xhr.onload = function () {    // do something to response    console.log(this.responseText);};xhr.send(data);


Use modern JavaScript!

I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

const url = "http://example.com";fetch(url, {    method : "POST",    body: new FormData(document.getElementById("inputform")),    // -- or --    // body : JSON.stringify({        // user : document.getElementById('user').value,        // ...    // })}).then(    response => response.text() // .json(), etc.    // same as function(response) {return response.text();}).then(    html => console.log(html));