Cross-Domain AJAX doesn’t send X-Requested-With header

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.”

Leave a Comment