I'm new to php,JSON, and js.
My problem is my php has somehow receive unquote json string from js.
I already print the json string after passing it through the function JSON.stringify
. and i get a normal json string with quote
This is my js script:
function post()
{
var test1 = {
name:"marzzuq",
age:16
};
myjson = JSON.stringify(test1);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","post.php",true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(myjson);
console.log("\nsend ok: " + myjson);
}
and i get this from console.log
send ok: {"name":"marzzuq","age":16}
and this is my php script:
<?php
$rawdata = file_get_contents('php://input');
`echo $rawdata >> /tmp/test.txt`;
$JSON = json_decode($rawdata,true);
` echo test2 > /tmp/test.txt` ;
switch (json_last_error()) {
case JSON_ERROR_NONE:
`echo ' - No errors' >> /tmp/test.txt`;
break;
case JSON_ERROR_DEPTH:
`echo ' - Maximum stack depth exceeded' >> /tmp/test.txt`;
break;
case JSON_ERROR_STATE_MISMATCH:
`echo ' - Underflow or the modes mismatch' >> /tmp/test.txt`;
break;
case JSON_ERROR_CTRL_CHAR:
`echo ' - Unexpected control character found' >> /tmp/test.txt`;
break;
case JSON_ERROR_SYNTAX:
`echo ' - Syntax error, malformed JSON' >> /tmp/test.txt`;
break;
case JSON_ERROR_UTF8:
`echo ' - Malformed UTF-8 characters, possibly incorrectly encoded' >> /tmp/test.txt`;
break;
default:
`echo ' - Unknown error' >> /tmp/test.txt`;
break;
}
?>
at the end of the function, when i access /tmp/test.txt, i get this:
{name:marzzuq,age:16}
Why i get an unquote string? I was supposed to get quoted string correct? something like this:
{"name":"marzzuq","age":16}