If you’ve ever needed to make a cross-domain call via AJAX you’ve probably run into the dreaded same origin policy: The policy permits scripts running on pages originating from the same site to access each other’s methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites. Today I’ll show you how you can use JQuery to easily do this and I’ll do it with the additional help of PHP.
Note: With HTML5 a method was formalized for this particular thing (cross-domain calls) and it’s known as the postMessage interface. It would be great to use this but sadly it’s not implemented on all browsers yet and of course HTML5 has yet to fully reach maturity so things can change (take a look at the recent changes with WebSocket circa 2010 early 2011).
The easy part is setting up a PHP page to listen for incoming data and send back a result. Not only will we send back data but we will also send back the function name we want to call on the client’s browser. Here is the PHP code:
name = $_GET['name']; $obj->message = "Hello " . $obj->name; echo $_GET['callback']. '(' . json_encode($obj) . ');'; } ?>
You can see two parameters come in: name and callback
Note: Keep in mind when you go to test this that you put your HTML file on one site and the PHP file on a different one and that way you can assure it’s working. If you put both the PHP and HTML file on the same site JQuery will actually just default back to a regular AJAX call from what I’ve read.
The HTML file is actually pretty simple as well if your familiar with JQuery AJAX:
This creates a simple HTML page with a button and clicking on it produces the desired result (see below).
There are two things to note here:
1. You need to set the dataType as jsonp
2. Setting jsonp to callback and then setting jsonpCallback to jsonpCallback makes the querystring look like this:
Calling the PHP file with the proper querystring produces a result like this:
Running the code from the HTML page will simply display the results.
Update Sept. 21, 2011: A reader pointed out he had some issues with the PHP code in this article and needed to add an additional header to get this to work. If your having issues please try adding these headers to your PHP code:
header("content-type: Access-Control-Allow-Origin: *"); header("content-type: Access-Control-Allow-Methods: GET");
Another thing to keep in mind if your using a hosting service or you don’t have complete control over the server that hosts your server side logic, it’s possible your host might block this type of thing (JSONP) as seen in the below Apache config:
Header set Access-Control-Allow-Origin "mydomain.com"
Make sure to check with your web host.