Send Post Data Using Xmlhttprequest

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

XMLHttpRequest not sending POST data

The problem is in your Content-Type. If you use application/json the PHP won't parse the post data into $_POST variable. You have to send them as form data to have PHP parse it.

See this question for more info Send POST data using XMLHttpRequest

Alternatively you can use file_get_contents("php://input") to get the raw body of HTTP request and parse the json with json_decode.

Example with file_get_contents and json_decode

PHP Code:

$in = file_get_contents('php://input');
$decoded = json_decode($in, true);
$data = new stdClass();
$data->msg = 'PHP is working';
$data->user = $decoded['user'];
$data->pass = $decoded['pass'];
echo json_encode($data);

JS Code:

var data = { 'user': 'myUser', 'pass': 'myPass' };

var xhr = new XMLHttpRequest();
xhr.open('POST', 'myUrl', true);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var res = JSON.parse(xhr.response);
console.log(res);
}
};

xhr.send(JSON.stringify(data));
return false;

Please notice that you need to JSON.stringify the data object before passing it as argument to send() method. Otherwise the data are not send correctly.

How to Send a body of data to XMLHttpRequest that looks like this?

var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = requestComplete;
xhr.send(JSON.stringify(params));

It looks like you just needed to stringify your params before passing them to send()

Passing multiple parameters by POST using XMLHttpRequest and HTML

The data variable you are using needs to be a JSON object. In your example here it is a string, so the individual values are not passed, just one single string.

Try:

var data = `{"ssid": "${network}", "psk": "${presharedkey}"}`;


Related Topics



Leave a reply



Submit