On a server it can be useful to know that an incoming request is AJAX.
Most js libraries use XMLHttpRequest
and so provide HTTP_X_REQUESTED_WITH: XMLHttpRequest
, but neither Chrome's implementation nor Github's polyfill of the new fetch
uses a similar header. So how can one detect that the request is AJAX?
Why is a request identifying its initiator not enforced through standards for fetch
and XMLHttpRequest
? Should something else be used for decision-making (e.g. clients providing the content-type they expect in response)?
By determining the readyState property value of XMLHttpReqyest, One can know if the request is completed. If the readyState value = 4, the request has been completed and the data is available.
The Fetch API doesn't cause any unique headers to be sent. If you just want to detect if a request probably came from frontend code running in a browser, you can by checking for the Origin header. Browsers add the Origin header to all cross-origin GET s.
Fetch is compatible with all recent browsers including Edge, but not with Internet Explorer. Therefore, if you are looking for maximum compatibility, you will continue to use Ajax to update a web page. If you also want to interact with the server, the WebSocket object is also more appropriate than fetch.
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers.
Check out this issue on the Github's polyfill repository, specially this comment.
Since the X-Requested-With
header is not an standard, they are using a wrapper that provides some of the missing behavior.
If you need more guidance, check this lines of the wrapper code:
function headers(options) {
options = options || {}
options.headers = options.headers || {}
options.headers['X-Requested-With'] = 'XMLHttpRequest'
return options
}
Why is a request identifying its initiator not enforced through standards
Because it shouldn't matter.
HTTP clients ask for the thing they want to get. The server should give it to them.
Giving clients something different based on what the client is tends to cause more problems than it solves. User-Agent sniffing being a prime example.
Should something else be used for decision-making (e.g. clients providing the content-type they expect in response)?
Yes.
The Accept
header is specifically provided for allowing a client to specify which format they would prefer the data in when an HTTP resource is available in multiple formats.
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