Cross-Domain AJAX calls using PHP

AJAX has become the core component of many web applications around us. And its fairly easy to handle AJAX now a days, with the help of various javascript libraries (ex: jQuery, Prototype, Mootools, YUI, etc). But there is one security issue that web browsers impose in doing AJAX calls – they don’t let you do AJAX calls in web servers different than yours. That means, if your script is in and you’re trying to do AJAX call to, then the browser will through error like: “Error: uncaught exception: Permission denied to call method”.

Now, there are a number of solutions to this problem. Instead of explaining them all to you, lemme provide you the simplest one: using a PHP transport file. If you already know the thing and just need the script, download from here.

Others, let’s see an example implementation first.

Example use

   1: xmlHttp.onreadystatechange=function()
   2: {
   3:     if(xmlHttp.readyState==4)
   4:     {
   5:         alert(xmlHttp.responseText);
   6:     }
   7: }
   9:"GET", '' +
  10:                     urlencode('') +
  11:                     '&method=get&data1=101&data2=pass', true );
  13: xmlHttp.send(null);

Now, lets see how it works:

  1. The script makes an AJAX call to the with a few parameters:
    • action = the target URL you need to fetch, from a different domain
    • method = the HTTP method (post/get)
    • data1, data2 = sample parameters for using as either query-string or POST fields
  2. When the request is received by transport.php, it uses cURL to make a call to the page mentioned in action.
  3. Based on the method, it either makes a GET request or a POST request. In both cases, it sends the extra parameters that are sent.
  4. After the response is received, transport.php echoes it. So, you have what you need!


Cross-Domain AJAX call transporter.
Downloaded: [downloadcounter(transport)] times


By dbglory Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s