Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a php variable in json and pass to ajax

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?

like image 727
Nevin Avatar asked Sep 19 '12 04:09

Nevin


1 Answers

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
));
like image 79
Will Palmer Avatar answered Oct 03 '22 06:10

Will Palmer