Hello i am trying to send fields from a from that i saved in a javascript object to a php server. I am using ajax but when i try to receive the object in php i get a length of 0 when debugging. Basically i can't receive the data. Please what did i do wrong.
Javascript code:
//fields from from saved in an object.
var obj={
'user_name': username,
'pwd': psswd1,
'user_email': email,
'user_phone': mobile,
'sec_quest1': question1,
'ans1': answer1,
'sec_quest2': question2,
'ans2': answer2,
'user_address': address,
'user_userInfo': user_info
};
console.log(obj);
var data = JSON.stringify(obj)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//document.getElementById("txtHint").innerHTML = xhttp.responseText;
alert(xhttp.responseText);
}
}
xhttp.open("POST", "server.php", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(data);
}
php code:
<?php
$obj = json_decode($_POST["data"]);
echo 'Name: '.sizeof($obj);
?>
It displays a size of zero meaning it's not receiving the data. Please what did i do wrong
You cant access the post variable when posting JSON to the server so you need to do this.
$str = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str, true);
Then retrieve the fields
$name = $response['user_name'];
$phone = $response['user_phone'];
// etc
// or just $response[0], $response[1], $response[2] etc etc
Basically the same answer as techblu3 above, but a little more detailed.
You might be posting raw data, that can be accessed in php in this way
$obj = json_decode(file_get_contents("php://input"),true);
// true parameter is used to decode as array
// you can make it false to use object
echo $obj["user_name"];
One solution would be serializing your data so you can send it with header x-www-form-urlencoded.
serialize = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
var obj = {
'user_name': 'John Doe',
'user_email': 'john@doe.net',
'user_phone': '2122221111',
};
var params = serialize(obj);
var url = "https://url.net";
console.log(params);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
Your PHP file would would include
<?php echo 'Name: '.sizeof($_POST); ?>