How to Make a Cross-origin Ajax Request

  • google plus

In Brief...

Cross-origin Resource Sharing (CORS) is a mechanism for requesting fonts, scripts, and other resources from an origin (defined, as above, as the combination of domain, protocol, and port) other than the requesting origin.

Take our Ajax Training course for free.

See the Course Outline and Register

Instructions

For instance, if sending a request from http://www.example.com, any of the following would be "cross origin":

  • http://mail.example.com (domain differs)
  • https://www.example.com (protocol differs)
  • http://www.example.com:8080 (port differs)

and, thus, scripts (or font, or other similar resources) would be blocked from these "foreign" sites. CORS offers a way for two sites to allow safe sharing of resources. CORS defines the communication between browser and server: specific headers in the HTTP request and HTTP response tell the browser that it's OK to accept the resource. At its most basic, a server issuing an HTTP response which includes the header

Access-Control-Allow-Origin: *
is allowing access from all requesting domains. A more-restrictive response, for example
Access-Control-Allow-Origin: http://www.example.com

would allow access only from a particular domain.

The great thing for us, as web developers, is that CORS-enabled responses work just like responses from our own (same-origin) site: our code can process the JSON, XML, or other response we receive just as if we were making a request of a page or resource on our own server.

The CORS request/response cycle can get significantly more complex, with "preflight" requests sent by the browser and responded to from the server, before another set of request/response; the passing of cookies or other authentication mechanisms; and other sharing of data. Check out http://www.html5rocks.com/en/tutorials/cors/, an excellent tutorial on HTML5 Rocks, to delve deeper into the topic. Check out http://enable-cors.org/resources.html#apis for a list of sites that offer CORS-enabled resources.

For these examples to work, more files are required than are available in this how to. To see these examples in action, take the Ajax training course.

  1. Let's look at an example, accessing a CORS-enabled site and a not-CORS-enabled site.
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>CORS - HTML5Rocks and NY Times</title>
    <style>
    	#ResponseContent {
    		width:66%;
    		padding:1% 2%;
    		background-color:#ccc;
    		margin-top:20px;
    	}
    	h2 {
    		margin:0;
    		padding:0;
    	}
    </style>
    <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
    	$(document).ready(function() {
    		$('#btnhtml5rocks').click(function() {
    			$('#ResponseContent h2').html('Response Content');
    			$('#ResponseContent div').html('');
    			$.ajax({
    				type: 'GET',
    				url: 'https://www.html5rocks.com/en/tutorials/file/xhr2/',
    				success: function(response) {
    					var article = $(response).find('article').first().html();
    					$('#ResponseContent h2').html('Response Content - from HTML5Rocks');
    					$('#ResponseContent div').html(article);
    				}
    			}).fail(function() {
    				alert("failed!");
    			});;
    		});
    		$('#btnnytimes').click(function() {
    			$('#ResponseContent h2').html('Response Content');
    			$('#ResponseContent div').html('');
    			$.ajax({
    				type: 'GET',
    				url: 'http://www.nytimes.com/',
    				success: function(response) {
    					var article = $(response).find('article').first().html();
    					$('#ResponseContent h2').html('Response Content - from NY Times');
    					$('#ResponseContent div').html(article);
    				}
    			}).fail(function() {
    				alert("failed!");
    			});
    		});
    	});
    </script>
    </head>
    <body>
    	<button id="btnhtml5rocks">Fetch HTML5 Rocks</button>
    	<button id="btnnytimes">Fetch NY Times</button>
    	<br>
    	<div id="ResponseContent">
    		<h2>Response Content</h2>
    		<div></div>
    	</div>
    </body>
    </html>
  2. Now let's dissect this code to see how it works. We include jQuery via a script tag, and use jQuery to effect our Ajax calls.
  3. The page presents two buttons, with ids btnhtml5rocks and btnnytimes, respectively, and use jQuery to listen for a click on each button.
  4. When either button is clicked, we make an Ajax call to a remote site, setting the h2 tag's content to show from which source we receive the external data and setting the contents of #ResponseContent div, if successful in our Ajax call, to the contents of the first article tag from our received response.
  5. Clicking the "Fetch HTML5 Rocks" button generates an Ajax call (via jQuery's $.ajax method) to http://www.html5rocks.com/en/tutorials/file/xhr2/. We set local JavaScript variable article to the contents of the first article found in the returned response and display the contents on our page.
  6. Despite our making a call to a cross-origin (i.e. non-local) site, our code works. Specifically, it is the presence of the Access-Control-Allow-Origin: * response header that tells our browser it is OK to allow this Ajax call: Cors HTML
  7. Clicking the "Fetch NY Times" button, conversely, doesn't work: the jQuery method .fail(), which we chain on to the end of the $.ajax call to http://www.nytimes.com/, generates a popup alert. If we inspect the response headers, we would find no Access-Control-Allow-Origin: * among them. If we check the console, we find that our browser complains of our attempt to violate the same origin policy: Cors Popup
  8. In large part, CORS depends on the server responding with the appropriate headers; if that is the case then, conveniently, our work as client-side developers becomes relatively easy, pretty much the same as if we were working with resources on our own server.

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss