Enable cross-origin resource sharing for AJAX

Enable cross-origin resource sharing for AJAX

A common problem when dealing with AJAX scripts is that the server script (or API) which javascript is calling is required to be on exactly the same domain (subdomain included).  To open up your server script / API to all domains the following headers are required to be sent before any content:

Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With

In PHP the code would be:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');

If you are using a single script that contains both the API and the regular page (even with includes), the headers must be sent before it is determined whether it is an API call or not.  This is due to a ‘pre-flight request‘ the browser does to test that the impending AJAX call is all approved and above board.  Once it receives the a-ok it will do a second call with the full AJAX credentials.