Hi Programmers,

Heard about JSON, and wandering how the hell you gonna implement it with PHP. And why would one use JSON when you have ajax and other alternatives. Well first of to understand JSON, i would recommend you to go through the JSON introduction part which i covered in my earlier post.

Now coming straight to the point, i am gonna cover the following things in this post

1) Prepare JSON string using php using json_encode() and send it to client side

2) Make the object from JSON string using eval()

3) Use this Object at client side using javscript.

$array=array(	a=>"One",
				b=>"Two",
				c=>"three"
			);
$json=json_encode($array);

The above php code, encodes an array of php into JSON string. That means this string can be sent to the client side and is a useful data for us. This data can be anything you like. You can pull this data from the database and then can manipulate at the client side as required using javascript. The function json_encode, encodes the given array in the JSON format. I have stored the string in the varibal $json and then embeded in the html using hidden field, shown below.

<html>
<head>
<title> JSON with Realin</title>
<script type="text/javascript">
function parseMe(){
var json=document.getElementById("json_text").value;
 
var obj=eval('('+json+')');
document.createElement("ul");
for(val in obj){
	alert(obj[val]);
}
 
}
</script>
</head>
<body>
 
<form>
<input type="hidden" id="json_text" value='<?php echo $json; ?>' />
<input type='button' value="parse" onclick="parseMe();" />
</form>
</body>
</html>

The above HTML has the value of that JSON string in the hidden field. If you are using some sorta template engine then you can assign this string the variable used in your template engine. For example in fast template i will do, $templateobject->assign(‘JSON_OBJ’,$json);

This data can be used as you want to, very soon i will post a blog entry which lets you sort the table data using this JSON data.

Leave comments,

Cheers !!

Realin !

Share this post: