Links

Cross site AJAX request

For cross site AJAX request we need following headers in host site:


Access-Control-Allow-Origin : http://example1.com, http://example2.com, ..
( it is necessary to mention requesting sites reference for localhost we can use http://127.0.0.1 and to grant access to all sites we can also use * )
 
Access-Control-Allow-Headers : Header1, Header2, ..
(we need to mention the permissions for headers send by other site)

Access-Control-Allow-Methods : POST, OPTIONS, ..(we also need to mention Request methods supported by our site for other sites GET is by default open)



Like if we have to send an AJAX request from http://our-site.com to http://www.example-host.com/ and we written following code in JavaScript

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.example-host.com/",true);
xmlhttp.onreadystatechange = function() { alert(xmlhttp.responseText); }
var param = '';
xmlhttp.setRequestHeader("SOAPAction", "http://www.example-host.com/Get");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(xml);

When we run the code it will give the error that 

XMLHttpRequest cannot load http://www.example-host.com/. Origin http://our-site.com is not allowed by Access-Control-Allow-Origin.

To resolve this we need permissions from hot site, in host site (ie http://www.example-host.com/) if we suppose the server side script is in PHP  we need to set permission headers for client

header("Access-Control-Allow-Origin : http://our-site.com");
header("Access-Control-Allow-Headers : SOAPAction, Content-Type");
header("Access-Control-Allow-Methods : POST");
?>

Post a Comment