First lets create a client page. In html part. We keep a div with certain id where our ajax returned data will be replaced. Now in scripting part we use getJSON function. Assumed you have already included jQuery library file.
getJSON takes three parameters. One is url from where we are going to fetch. Second is the data to be sent and third parameter is callback function which would be executed if request is successful. You may be thinking why there is ‘callback=?’ in the url. This is used to treat the request as JSONP instead. JSON only allows the request under same domain whereas JSONP also supports cross-domain request.
Now lets setup our server page.Here is the example php page.
<?php date_default_timezone_set('Asia/Katmandu'); $json_encoded=json_encode(getdate()); $callback=$_GET['callback']; $op=$callback.'('.$json_encoded.')'; header('Content-type: text/html'); echo $op; ?>
In server we need to echo our data in JSON format. PHP has ‘json_encode’ function which can convert array into json encoded form. In the example, I have fetched current date & time and it is json encoded. There is little hack in the code. jQuery excepts the returned data as callbackFunction(json_data). This callbackFunction is automatically replaced in ? by jQuery while requesting. Here header content type is ‘text/html‘ . I tried with ‘application/json’ but it gives error ‘invalid label’ in firebug. So I tried ‘text/html’ and it
You can get twits from Twitter in JSON format. Use following url in $.getJSON function in jQuery. You need to replace USERNAME with your desired twitter screenname.