Making cross-domain AJAX possible with your PHP backend


Nitin Venkatesh's Gravatar

Nitin Venkatesh
published March 7, 2014, 6:42 p.m.


Generally, browsers will not allow you to make AJAX calls to your scripts that reside on another domain because of the Same-Origin Security policy present by default. This can be circumvented by using JSONP and stuff, but what if your script only returned text as output? You could tweak your script to wrap the text output in JSON which would be the better idea, but, there's another way - setting the HTTP response headers.

<?php
switch ($_SERVER['HTTP_ORIGIN']) {
    case 'http://originating-domain.com': case 'https://originating-domain.com':
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    break;
}
?>

We use a switch case on the HTTP_ORIGIN server variable and set a case for the http and https versions of our sites. If this condition is satisfied, set the Access-Control-* headers and that's it. Easy-peasy, huh?

Additional Reading: