6

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?

5 Answers 5

19

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
));
Sign up to request clarification or add additional context in comments.

Comments

6

You should use json_encode to encode the data properly:

$data = array(
    "result" => $result,
    "count"  => 3
);
echo json_encode($data);

Comments

2

You're using single quotes in your echo, therefore no string interpolation is happening

use json_encode()

$arr = array(
    "result" => $result,
    "count" => 3
);
echo json_encode($arr);

As a bonus, json_encode will properly encode your response!

1 Comment

I have tried this too. but it shows the same echo '{ "result":"'.$result.'", "count":3 }';
0

Try:

$result = 'Hello';
echo '{
   "result":"'.$result.'",
   "count":3
}';

Comments

0
$result = 'Hello';

$json_array=array(
  "result"=>$result,
  "count"=>3
)
echo json_encode($json_array);

That's all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.