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:

// this will allow any domain to load this file via XHR / AJAX
<?php header("Access-Control-Allow-Origin: *"); ?>

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

// I haven't gotten this to work yet, but the documentation instructs to do as such
<?php header("Access-Control-Allow-Origin:"); ?>

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:

Header add Access-Control-Allow-Origin "*"

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p> <pre>
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or "class="OPTIONS" title="the title".
  • Lines and paragraphs break automatically.
  • E-Mail addresses are hidden with reCAPTCHA Mailhide.

More information about formatting options

Complete this form and then pat yourself on the back.