Cross-domain XHR

I learned about a new feature and decided I would share light with the rest of the web. I’m working on a YUI application for YAP and it’s causing trouble in the app because it’s forcing cross-domain loading of an XML file I need to load. However, it’s their platform and thus, their rules. Anywho, you can allow your files to be loaded to another domain by added a simple header to your file.

This can be done easily in PhP by adding the following code to your PhP file:

{syntaxhighlighter brush: php;gutter: false; fontsize: 100; first-line: 1; }// this will allow any domain to load this file via XHR / AJAX
<?php header(“Access-Control-Allow-Origin: *”); ?>{/syntaxhighlighter}

Oh another note, lets say you want to restrict your file to a certain domain of jacksonkr.com:

{syntaxhighlighter brush: bash;gutter: false; fontsize: 100; first-line: 1; }// I haven’t gotten this to work yet, but the documentation instructs to do as such
<?php header(“Access-Control-Allow-Origin: http://jacksonkr.com”); ?>{/syntaxhighlighter}

Here’s a couple helpful resources: Request Headers article from w3 and HTTP Access Control from Mozilla.

Lastly, here’s the XHR article that I discovered originally.

Edit on 8/2/2011

It turns out you can use an htaccess file to allow cross-domain access as well. To allow all traffic you will need to add the following to your .htaccess file:

{syntaxhighlighter brush: php;gutter: false; fontsize: 100; first-line: 1; }Header add Access-Control-Allow-Origin “*”{/syntaxhighlighter}

Leave a comment

Your email address will not be published.