More Than Just Web Design | INTERNET ENGINEERING | APPLICATION | DESIGN

Busting For a P

Posted: 19/11/12

The AJAX cross domain policy can be rather annoying but there is a way around it

I needed to make two different sub domains work together recently, producing a page on one site by using parts of another. Because they're different sites, the AJAX Same Origin Policy comes in to play, and in short it stops you from doing it.

Fortunately the solution is to use jQuery's getJSONP() function, which is not subject to those restrictions. It can take a few moments to grok what's going on here, but in essence your client side request looks like this:

function myfunc(data) {
        $('#mydiv).html(data.mydata);
}
$.getJSON('http://sub.domain.co.nz/myphp.php?callback=?');

and your server script looks like this:

echo "myfunc(".json_encode(array('mydata'=>'awesome')).")";

The important points to note are:

  1. Your server returns a json response, which sits in the middle of myfunc() i.e.
    myfunc({"mydata":"awesome"})
  2. Your client must have a function named myfunc defined, which will receive the json payload as its first argument
  3. The client side callback=? parameter is vital