Do you want to grab server-side data easily through ajax? Like using the famous jQuery.ajax method?

Well then all you need is JavaScript Object Notation known as JSON. Compared to XML, JSON is more lighter and faster since it can be recognized natively by JavaScript. You can now do that as easily as 1, 2, 3.

Providing JSON and JSONP easily in PHP

Just set the content-type to application/json on your server side code and use json_encode function to encode your data and just echo it out.

<?php
header('Content-type: application/json; charset=utf-8');
$data = array( 'apple', 'orange', 'strawberry', 'lemon', 'pear' );
echo json_encode( $data );
?>

You can view the request being done in the console of your browser but others encounter this problem due to browser security restrictions, most “Ajax” requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

All you have to do if you encounter that problem is to add a padding with your JSON, also know as JSONP, a simple and nice solution to your problem.

Mr. Wiki says that

JSONP or “JSON with padding” is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server.

I already experienced the same problem and I find JSONP very useful in troubleshooting this problem. It’s just the same as plain JSON, the only difference is just to wrap your JSON encoded data in a callback function provided using the $_GET parameter.

<?php
header('Content-type: application/json; charset=utf-8');
$data = array( 'apple', 'orange', 'strawberry', 'lemon', 'pear' );
echo $_GET['callback'] . '('.json_encode($data).')';
?>

You can also provide both formats as easy as how you do the first step. You just need to check if the callback parameter is set or not.

<?php
header('Content-type: application/json; charset=utf-8');
$data = array( 'apple', 'orange', 'strawberry', 'lemon', 'pear' );
$json = json_encode($data);

echo isset($_GET['callback'])
 ? "{$_GET['callback']}($json)"
 : $json;
?>

But another thing to consider is that you can able to use this on a cross-domain process. Because of the security in oyur browser our current code will not work cross-domain. So, if you want everyone to access to your JSON data, all you need to do is to add a single header to your code:

<?php
header('Content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

$data = array( 'apple', 'orange', 'strawberry', 'lemon', 'pear' );
$json = json_encode($data);

echo isset($_GET['callback'])
 ? "{$_GET['callback']}($json)"
 : $json;
?>

Now you can access your data from everywhere.

That’s it! We are all done and I hope you’ll find this useful.

Original Source: http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/

Avatar Image

Raymond Serion

To Fear God is the beginning of Knowledge...