PHP Loves JSON
JSON is a format for communication between the server-side (PHP, JSP, ASP, etc…) and the client-side (javascript). The magic of it is that the response from the server-side can be easily converted to an object via the use of the eval() function. eval() (can be “evil”) is a function that gives you the possibility to execute some code in javascript from a string. To use eval() is not a good idea.
How can you JSON from PHP?
If you are using PHP 5.2.x and above, you can simply use PHP built-in function, json_encode() and json_decode(). This is an example how it works:
$i = array(
array(“id” => 1, “name” => “sumardi”),
array(“id” => 2, “name” => “hassan”),
array(“id” => 3, “name” => “ruby”)
);
echo json_encode($i);
And it will echo :
[{"id":1,"name":"sumardi"},{"id":2,"name":"hassan"},{"id":3,"name":"ruby"}]
How to JSON on Client-Side?
Use the eval() function on the Server-Side JSON text response. And then you can call JSON like this:
for(var i = 0; i < json.length; i++)
{
console.info(json.id + " " + json.name);
}
Pingback: links for 2008-09-08 — Mior Muhammad Zaki: PHP & JavaScript Programmer