Thursday 13 January 2011

Cross Domain AJAX

The other day I was looking for a simple way of accessing a foreign domain using AJAX - I needed to POST some data to a 3rd Party webservice. JavaScript opens up a few different ways of solving this problem, but most of them require some addition (a file normally) to be placed on the foreign domain web server - this option was not open to me. So I decided to create a simple proxy in PHP - the idea is that I would use JavaScript to POST using AJAX to the PHP script, and then the PHP script would connect to the 3rd party, POST the data and then return the value back to the JavaScript callback. Below is the code I used.

Firstly the PHP proxy script
//open curl connection
$cc = curl_init();
// get url from $_GET
$url = $_GET['url'];
// set the curl url
curl_setopt($cc, CURLOPT_URL, $url);
// set return option
curl_setopt($cc, CURLOPT_RETURNTRANSFER, true);
// set method to POST
curl_setopt($cc, CURLOPT_POST, 1);
 
// loop the $_POST entries and save
foreach ($_POST as $name => $value){
    $data[$name] = $value;
}

// set the post data
curl_setopt($cc, CURLOPT_POSTFIELDS, $data);
 
//execute curl post
$result = curl_exec($cc);
 
//close connection
curl_close($cc);
 
echo $result;

Very simple script - basic cURL setup between lines 01 and 10. The loop at line 13 goes through the POST values sent to the proxy and stores them in a variable for use later in the script. Line 18 sets up the POST data and line 21 sends the request. The cURL connection is then closed and the result is sent back the caller (JavaScript) on line 26.

The JavaScript is equally as simple (below I am using YUI Connection Manager)
// Example POST data
var postData = "name1=value1&name2=value2&name3=value3;

// Handle Success
var handleSuccess = function(o){
  // Handle a success - output to console
  console.log(o.responseText);
}
// Handle Failure
var handleFailure = function(o){
  //handle failure calling URL
  console.log(o.statusText);
}

// Setup callback 
var callback =  {
  success:handleSuccess,
  failure:handleFailure
};
  
// setup the url of the proxy script
// passing the foreign url in as a parameter
var callurl = "/proxy.php&url=http://www.google.co.uk/";
// make the AJAX request
YAHOO.util.Connect.asyncRequest('POST', callurl, callback, postData);
As you can see - very simple - setup the POST data on line 02, setting up the handlers between lines 05 and 19. The final 2 lines (23 and 25) setup the URL to the proxy we created above and the actual AJAX call to the script.

2 comments:

  1. Thanks for explonation. What about platform specific? I mean here is info for yahoo http://developer.yahoo.com/javascript/howto-proxy.html and what about MicrosoftAjax? I've tried your code and got |error|500. But it better than yahoo-code. that returned whole page.

    I think its lack of setopt parameters

    ReplyDelete
  2. What platform are you using ? this was using Apache running on Windows

    ReplyDelete