Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

Cross-Domain AJAX Requests

Cross-domain AJAX requests aren’t possible, but there are ways to leverage a server-side language to work around this issue. In this section, I’ll discuss how to use PHP to create a bridge between the AJAX request and a remote RSS feed, in order to achieve cross-domain requests. I think that you’ll be extremely surprised at just how easy it is.

PHP has a native method called file_get_contents, which reads an entire file into a string. This file can be a remote file if fopen wrappers is enabled, which it is by default when you install PHP. It’s only disabled if allow_url_fopen is set to off in the php.ini file. The following code is the contents of the bridge.php file, which we’re requesting with index.html when we submit the form:

  header("Content-Type: application/xml; charset=UTF-8");
  echo file_get_contents($_GET[’feed’]);

The first line of code is a header that will set the content type of the response to valid XML for our requesting object. file_get_contents then is used with the combination of the feed URL that was passed through our request from the form in the index.html file. Once the data is ready, the AJAX engine delegates it to the callback method, which is our Aggregator object.

  • + Share This
  • 🔖 Save To Your Account