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 www.mydomain.com and you’re trying to do AJAX call to www.anotherdomain.com/get.php, then the browser will through error like: “Error: uncaught exception: Permission denied to call method XMLHttpRequest.open”.

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: }
   8:  
   9: xmlHttp.open("GET", 'http://myserver.com/transport.php?action=' + 
  10:                     urlencode('different-server.com/return_call.php') +
  11:                     '&method=get&data1=101&data2=pass', true );
  12:  
  13: xmlHttp.send(null);

Now, lets see how it works:

  1. The script makes an AJAX call to the myserver.com/transport.php 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!

Download

transport.php
Cross-Domain AJAX call transporter.
Downloaded: 4346 times

Comments and suggestions are most welcomed :)

Share and Enjoy:
  • Digg
  • DZone
  • Twitter
  • Posterous
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Technorati
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Simpy
  • Ping.fm
  • Tumblr
Post rating
1 Star2 Stars3 Stars4 Stars5 Stars (12 votes, average: 4.17 out of 5)
Loading ... Loading ...

  • Wish all
    Hi,

    I am new to PHP. I couldnt find urlencode function in javascript. So to make it workable in my code, I have changed the urlencode to escape function.

    ie
    xmlHttp.open("GET", 'http://myserver.com/transport.php?action=' + 10: escape('different-server.com/return_call.php') + 11: '&method=get&data1=101&data2=pass', true );

    Is it correct?

    Regards,
  • Sumeet
    it gives error urlencode not found?
  • Piro
    My target page has '?page=x' to get the different contents according to x.
    In this case, this script ignores '?page=x' and it results in getting the default contents.

    Could you please give me some hints how to fix this problem.

    Thank you!
  • Nick Syed
    I am using the following code, I get an error saying Object Not Found, can you please help ?

    <html>
    <body>

    <script type="text/javascript">

    function ajaxFunction()

    {

    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
    {
    document.myForm.time.value=xmlHttp.responseText;
    }
    }
    xmlHttp.open("GET","transport.php?action="+urlencode("http://www.netshelter.net/time.php"),true);
    xmlHttp.send(null);

    }

    </script>

    <form name="myForm">
    Name: <input type="text" onkeyup="ajaxFunction();" name="username" />
    Time: <input type="text" name="time" />
    </form>

    </body>
    </html>
  • Hi, thanx a lot for the code!!

    I've made the following solution with Jquery + PHP:

    $.get("http://mydomain.com/transport.php?action=<? echo urlencode('http://www.anotherdomain.com'); ?>&method=get&var1=variable1&var2=variable2&var3=variable3",
    function(serverResponse) {
    alert(serverResponse);
    }
    );

    And I had to change the transport.php on the line 18 to: $action = $_REQUEST['action'];

    It worked very well!!

    Thx again
  • Nice to know that.
    Thank you
  • Hi, i've tried using your script and on my homeserver it runs fine but on my shared hoster it hangs at curl_exec().
    Is there anything you know of that causes this freezing/hanging?
  • Kelvin
    I have tried this proxy approach, but neither Firefox nor IE 6 will allow me to call a php page with XMLHttpRequest. Of course, it won't allow me to call webservice cross-domain either.
    Thanks.
  • François Labarde
    there's a typo:

    you wrote this:
    if ($key != 'url' || $key != 'method')

    while you obviously meant this:
    if ($key != 'url' && $key != 'method')


    (since ($key != 'url' || $key != 'method') is always true)
  • SuNcO
    On the transport file you can't get the action because is named url

    You must change that line :

    $action = $_REQUEST['url'];

    To :

    $action = $_REQUEST['action'];

    Or change this :

    xmlHttp.open(“GET”, ‘http://myserver.com/transport.php?action=’ + 10: urlencode(‘different-server.com/return_call.php’) + 11: ‘&method=get&data1=101&data2=pass’, true );

    With this :

    xmlHttp.open(“GET”, ‘http://myserver.com/transport.php?url=’ + 10: urlencode(‘different-server.com/return_call.php’) + 11: ‘&method=get&data1=101&data2=pass’, true );
blog comments powered by Disqus