thinkbuildblog

Cross-domain Ajax, part 2: Using cross-origin resource sharing

Posted by Tariq Chaudhry

In my last post I gave an example of how JSON-P can provide a solution to the restrictions that the same-origin policy places on asynchronous requests.  In the event when a developer wants to place an AJAX call between two different domains that she owns, JSON-P will allow this, but what if I want to allow others to access my content using AJAX?

I could provide the world with the JavaScript function signature that the content will be padded with, but that is sloppy and insecure.  The JSON-P method is really more of a hack that exploits the allowance of a different domain to insert JavaScript using the ‘script’ tag.

Where JSON-P is limited to GET only, Cross-Origin Resource Sharing, or CORS, allows us to make just about any HTTP request.  Cross-Origin Resource Sharing adds more control, better error handling, and more functionality.

The biggest drawback is that CORS in not 100% cross-browser compatible.  Wikipedia has a page that lists the supported browsers; as with many newer Internet techniques, Internet Explorer 8 has only limited support.

CORS works by implementing new HTTP headers.  These headers provide access controls that define which domains and methods are allowed access.

The best way to illustrate this would be to show an example.

On the domain that we want to access, there would need to be a ‘Access-Control-Allow-Origin’ header specifying our domain.  We would also need ‘Access-Control-Request-Method’ to specify which HTTP method would be allowed, (i.e. GET & POST)

This is an example PHP script residing on our test domain: http://anotherdomain.com

On our referring domain we would have this script:

This is only a basic example there are many more access controls and functionality in to the specifications for Cross-Origin Resource Sharing.  Although it is still in the working draft stage, you can read the specifications on w3c site here:  http://www.w3.org/TR/cors/

Happy developing!

Categories: Tech topics Tags: , , , , , Leave a comment
  • Tweet This
  • Like This
Tariq Chaudhry
About Tariq Chaudhry

Tariq has over 10 years experience in development and information technology, ranging from object oriented languages such as C++, PHP and Javascript to Linux system administration experience. He joined Pixafy in 2012.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">