Cross domain AJAX that is cross browser as well

This is just a quick and dirty post about cross domain AJAX. If you wanted to create a working cross domain AJAX but also needs to secure the ajax requests from other referring domains, this is what we can do.

AJAX with JSON request

Be sure your request is a JSON request, below is an example:

$.ajax({
    url: "http://your.other.domain.com/here/?",
    type: "GET",
    cache: true,
    contentType: "application/json",
    dataType: "json",
    success: function(data){
        // Success routine here
    },
    error: function(){
        // Error routine here
    }
});

Server response – set proper headers

For the server side of the AJAX request, we need to set proper headers that will allow the cross domain AJAX request. Below is the basic structure.

<?php
// ...
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
// ...

Securing the referrers

You may want to allow any domains to consume the AJAX response. However, in case you need to limit the domains who may call the AJAX to a few preselected domains, then you must do some checks to validate the referring domains.

Normally, we can see where the AJAX request comes from by looking at the HTTP_REFERER. This works for Google Chrome so far. However, for Firefox, we need to look at HTTP_ORIGIN instead since Firefox handles cross domain AJAX differently, in fact it uses OPTIONS requests instead of GET or POST. Sample code below in PHP.

<?php
// ...
$referrer = null;
if (isset($_SERVER['HTTP_REFERER'])) {
    $referrer = $_SERVER['HTTP_REFERER'];
} elseif (isset($_SERVER['HTTP_ORIGIN'])) {
    $referrer = $_SERVER['HTTP_ORIGIN'];
}
if ($referrer !== null) {
    $refDomain = Some_Helper::getInstance()->getAuthorizedReferrer($referrer);
    if ($refDomain !== null) {
        error_log($refDomain);
        $this->getResponse()->setHeader('Access-Control-Allow-Origin', $refDomain);
        // ...
    }
}
// ...

Note: There is currently an issue in IE8 wherein normal cross domain AJAX requests doesn’t work. Still investigation about the issue and possible easy solutions (XDR anyone?).

That’s it!

This entry was posted in php and tagged , , , . Bookmark the permalink.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *