Create a web service on http://www.a.com/service.asmx and send a cross-domain ajax request to it from http://www.b.com. Check the headers in Firebug, or in Live HTTP Headers, or any other plugin you wish.
There is no trace of the X-Requested-With HTTP Header field among request headers.
However, if you send an ajax request to the same service from the same domain (say for example http://www.a.com/about), you will see that header field.
Why is the X-Requested-With header field omitted for cross-domain ajax requests?
Update: I know that JSONP calls are not AJAX calls in nature. Thus you won't see any X-Requested-With header field, in JSONP calls.
Because of Same origin policy. The same-origin policy exists to prevent malicious use of resources. If there were no rules governing cross-domain script access, it would be trivial to wreak all manner of havoc on unsuspecting users.
Cross Domain AJAX Request. A common problem for developers is a browser to refuse access to a remote resource. Usually, this happens when you execute AJAX cross domain request using jQuery Ajax interface, Fetch API, or plain XMLHttpRequest. As result is that the AJAX request is not performed and data are not retrieved.
Browser does not allow cross domain AJAX requests due to security issues. Cross-domain requests are allowed only if the server specifies same origin security policy. To enable CORS, You need to specify below HTTP headers in the server.
The X-Requested-With is a request header that a user agent may use to store information about the creation of the request such as client information, method used. Note that the X-Requested-With cannot be added to a cross domain request without the consent of the server via CORS.
If you are using jQuery to do your ajax request, it will not send the header X-Requested-With (HTTP_X_REQUESTED_WITH) = XMLHttpRequest, because it is cross domain. But there are 2 ways to fix this and send the header:
Option 1) Manually set the header in the ajax call:
$.ajax({
url: "http://your-url...",
headers: {'X-Requested-With': 'XMLHttpRequest'}
});
Option 2) Tell jQuery not to use cross domain defaults, so it will keep the X-Requested-With header in the ajax request:
$.ajax({
url: "http://your-url...",
crossDomain: false
});
But with this, the server must allow those headers, then the server needs to print those headers:
print "Access-Control-Allow-Origin: *\n";
print "Access-Control-Allow-Headers: X-Requested-With, Content-Type\n";
The first line above will avoid the error "Origin is not allowed by Access-Control-Allow-Origin."
The second line will avoid the error "Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With