This question already has an answer here:
I encoded an array into JSON in javascript:
var data = JSON.stringify(cVal);
And here is my ajaxrequest object:
function ajaxRequest(url, method, data, asynch, responseHandler){
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST")
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
};
request.send(data);
}
and I send the json to php with this ajaxrequset:
ajaxRequest("setOrder.php","POST", data , true , dosetOrder);
in php side:
$array=$_POST['data'];
but system says that the data in a undefined index in php
</div>
var data = {};
data["username"] = username;
data["password"] = password;
var jsonData = JSON.stringify(data);
function ajaxRequest(url, method, data, asynch, responseHandler){
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST")
request.setRequestHeader("Content-Type","application/json");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
request.send(data);
}
$body = json_decode(file_get_contents("php://input"), true);
echo $body["username"];
//example with Slim PHP framework
$body = json_decode($app->request->getBody(), true);
echo $body["username"];