Using JQuery, AJAX and JSONP to do cross-domain calls with PHP

Post to Twitter

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.

[ad name=”Google Adsense”]

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:

	header("content-type: text/javascript"); 

	if(isset($_GET['name']) && isset($_GET['callback']))
		$obj->name = $_GET['name'];
		$obj->message = "Hello " . $obj->name;
		echo $_GET['callback']. '(' . json_encode($obj) . ');';

You can see two parameters come in: name and callback
The name is some user defined string, in this case I will use my actual name. I then format the response to be JavaScript.

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:

<!DOCTYPE html>
<html lang="en">
    <title>JQuery JSONP</title>
    <script src=""></script>

				url: '',
				data: {name: 'Chad'},
				dataType: 'jsonp',
				jsonp: 'callback',
				jsonpCallback: 'jsonpCallback',
				success: function(){

	function jsonpCallback(data){
    <input type="button" id="useJSONP" value="Use JSONP"></input><br /><br />
    <span id="jsonpResult"></span>

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:

jsonpCallback({"name":"Chad","message":"Hello Chad"});

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 ""

Make sure to check with your web host.

Post to Twitter

This entry was posted in JavaScript, PHP. Bookmark the permalink.

8 Responses to Using JQuery, AJAX and JSONP to do cross-domain calls with PHP

  1. Noel says:

    hi Chad…! i’ve used jQuery for less 2 years..but poor i do not know this jsonp method?? .. jsonp heck ease method save me a lot..question for you…how about the vulnerability??is it safe for data communication? how to compare this method with web service like soap??.. sorry for my bad english, i’m from Indonesia…..keeping on yours great work……

  2. Chad Lung says:


    If you control your end point or trust the endpoint you can make it pretty secure by using best practices, etc. Like anything though its only secure as the person writing the code.


  3. agam says:

    Thanks a lot for this great tutorial,
    Saved me plenty of time.
    I can theoretically implement this as the client side(html_+jquerY) of an API right?
    Or are there better ways to do so?

  4. Pingback: How to do a AJAX JSONP (Cross Site Domain request) « KaixersofT { ScriptBlocK } Weblog

  5. John says:

    Hey Chad I’ve tried the tutorial and i got the following error message:
    “Resource interpreted as Script but transferred with MIME type text/html.”

    any ideas? maybe should I add a mimeType to the ajax request? I’m stuck.

    Thanks in advance!

  6. Ishmael says:

    Hi guys, many thanks, I can now create my third party APIs with much ease using JSONP. No need to redirect third-party users to my site.

  7. says:

    Thanks a lot for this great tutorial,

Comments are closed.