With jQuery the Ajax function sets the header HTTP_X_REQUESTED_WITH
, so with PHP I could do:
if(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest')
{ ... }
And this will tell me the page has been requested using Ajax.
Now I'm wanting to change the Ajax
function to fetch()
. I've looked through the default headers that it sets and I can't find anything that I can use to to tell if the request is being sent from a fetch.
I could set the header myself:
fetch('/get/login', {
headers: {
'X-Requested-With': 'fetch',
},
})
.then(function(response) { ... }
However it isn't ideal to be writing that header out for every fetch. What are my options here? Is there a better way to tell if the request is being made through a fetch?
No, there is nothing else you can rely on.
Theoretically you shouldn't give your server different behaviour depending on request method; that should be orthogonal to the content defined by your system's back-end.
But, if you're desperate, I quite like your existing solution; you could wrap it in a function for brevity.
Since you are relying on the client side to pass the data, couldn't you pass a POST variable inside body? Passing a header via javascript is no more secure than simply passing an additional field. (https://davidwalsh.name/fetch)
fetch('/get/login', {
body: JSON.stringify({
source: : "fetch"
}),
})
.then(function(response) { ... }