Cross-site HTTP requests are HTTP requests at URL addresses other than the domain of the resource making the request. The CORS specification allows the server side (that returns the resource we try to retrieve using the XHR object) to serve the resource to requests coming from resources that were served from other domains.

According to the CORS specification the server side that returns the requested resource can return the Access-Control-Allow-Origin header in order to specify domains that it will possible to initiate the request from resources they served.

The following code sample includes two files. The first is an HTML file that includes code in JavaScript that uses the XHR object in order to send an HTTP request at a URL address of another domain from which the HTML file is served.

<!DOCTYPE html>
<html>
<head>
    <title>simple demo for http access control</title>
</head>
<body>
    <div id="result"></div>
    <script type="text/javascript">
        var xhr = new XMLHttpRequest();
        xhr.open("GET","http://www.abelski.com/courses/ajax/data.php",true);
        xhr.onreadystatechange = function()
        {
            if((xhr.readyState==4) && (xhr.status = 200))
            {
                var ob = JSON.parse(xhr.responseText);
                var str = "name="+ob.name+" id="+ob.id+" average="+ob.average;
                var node = document.getElementById("result");
                node.innerHTML = str;
            }
        };
        xhr.send();
    </script>
</body>
</html>

The second file is a PHP file that its output is in the JSON format. The PHP file returns its output together with the HTTP header Access-Control-Allow-Origin.

<?php
header("Access-Control-Allow-Origin: http://localhost:8888");
?>
{
    "name":"dave",
    "id":123123,
    "average":94
}
?>

The following video clip overviews this code sample, shows its execution and explains each and every part it includes.

You can find more code samples, video clips and training material for learning this topic in my free online courses website at http://abelski.lifemichael.com.

Leave a Reply

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