CORS (cross origin resource sharing) can be used to make AJAX requests to different origins. Here are some points to note:
- CORS un-aware browser will not make a CORS request.
- CORS aware browser will make CORS request with following header
Origin: http://requestingdomain.com
- Server must respond with the following header for a cross origin request to be honoured by CORS aware browser.
Access-Control-Allow-Origin: * ## or Access-Control-Allow-Origin: alloweddomain.com
This way CORS unaware server don’t have to worry about CORS as they will never server this response header.
- Requests made from iframe will use parent domain/host for
Origin
header - CORS is now supported in most modern browsers (Chrome, Forefox, IE11+).
CORS allow same domain example – request from same domain using jQuery
This is default case and everything works fine here. No extra request or reponse header due to CORS.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <div id="result1">-</div> <script type="text/javascript"> $.ajax({ url: "/demo2/cors/hello_allowed_from_same.php" }) .done(function( data ) { $("#result1").html(data); }); </script>
CORS allow same domain example – request from different domain using jQuery
Here jQuery adds the following CORS header automatically:
Origin:http://infoheap.com
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <div id="result1">-</div> <script type="text/javascript"> $.ajax({ url: "https://www.infoheap.com/demo2/cors/hello_allowed_from_same.php" }) .done(function( data ) { $("#result1").html(data); }); </script>
Since server does not respond with right CORS header, Chrome throws this error in console:
XMLHttpRequest cannot load https://www.infoheap.com/demo2/cors/hello_allowed_from_same.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://infoheap.com' is therefore not allowed access.
Note that here server actually served the request unaware of CORS. It was client Chrome which blocked it after getting response from server.
CORS allow any domain example – request from different domain using jQuery
Here following request header is added by jQuery
Origin:http://infoheap.com
And the following response header by server:
Access-Control-Allow-Origin: *
So everything works fine and result is displayed.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <div id="result1">-</div> <script type="text/javascript"> $.ajax({ url: "https://www.infoheap.com/demo2/cors/hello_allowed_from_any.php" }) .done(function( data ) { $("#result1").html(data); }); </script>