My Code
var json = xmlhttp.responseText; //ajax response from my php file
obj = JSON.parse(json);
alert(obj.result);
And in my php code
$result = 'Hello';
echo '{
"result":"$result",
"count":3
}';
The problem is: when I alert obj.result
, it shows "$result"
, instead of showing Hello
.
How can I solve this?
The basic problem with your example is that $result
is wrapped in single-quotes. So the first solution is to unwrap it, eg:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
But this is still not "good enough", as it is always possible that $result
could contain a "
character itself, resulting in, for example, {"result":""","count":3}
, which is still invalid json. The solution is to escape the $result
before it is inserted into the json.
This is actually very straightforward, using the json_encode()
function:
$result = 'Hello';
echo '{
"result":'.json_encode($result).',
"count":3
}';
or, even better, we can have PHP do the entirety of the json encoding itself, by passing in a whole array instead of just $result
:
$result = 'Hello';
echo json_encode(array(
'result' => $result,
'count' => 3
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With