Technology

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

Posted by Pixafy Team

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

<?php
header('Access-Control-Allow-Origin: http://corstest.local');
header("Access-Control-Request-Method: GET, POST");
header('Access-Control-Allow-Headers: accept, origin, content-type');
?>

<html>
<head>
</head>
<body>
Hello World!
<h3>You entered this text.</h3>
<h2>"<?php echo $_POST['string']; ?>"</h2>
<h3>I made it look like this:</h3>
<h2 style="color:red">"<?php echo strrev($_POST['string']); ?>"</h2>
</body>
</html>

On our referring domain we would have this script:

<script type="text/javascript">
//<![CDATA[
      function sendText(form) {
      var client = new XMLHttpRequest();
      client.open("POST","http://anotherdomain.local/", true);
      client.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      client.onreadystatechange = function() {
            if (client.readyState == 4 && client.status == 200) {
                  document.getElementById('output').innerHTML =client.responseText;
            }
      }
      client.send('string='+form.elements[0].value);
}
//]]>
</script><form action="http://anotherdomain.local/" method="post">
      <input type="text" name="test" />
      <input type="submit" onclick="sendText(this.form); return false;"/>
</form>
<div id="output">
</div>

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!

Questions or comments? Share them below, or tweet us @Pixafy!