[PHP 5 + jQuery]: JSON Cross Domain

Here I will share how we can get data from another domain. Normally this will return an error as it’s involving cross domain, requested by one domain to another domain. This tutorial will be using PHP 5 along with jQuery.

First, let’s look at the source of the PHP file, (file name: process.php):

<?php
/*
 * @author Mohd Rashidi Bin Mohd Zin ([email protected])
 */

$text = $_GET['text'];
$callback = $_GET['callback'];

if (!empty($text))
{
    switch($text)
    {
        case 'Google':
            $return = 'The Oracle';
            break;

        case 'Yahoo!':
            $return = 'Morpheus';
            break;

        case 'MSN':
            $return = 'Mr Smith';
            break;

        default:
            $return = 'Who the heck?';
            break;
    }

    echo $callback.'('.json_encode(array("result" => $return)).')';
}
?>

This is the file which will store on a different domain. As you can see, the file accepts two inputs; user’s input and name of the callback function. It is important to mention name of the callback function, otherwise Firefox will return an error “invalid label”, while other browser will not display anything.

In the end, the file will return a string consists of name of the callback function and the encoded JSON.

Continue reading “[PHP 5 + jQuery]: JSON Cross Domain” »