Jump to content

is ajax request


Destramic

Recommended Posts

hey guys im tring to look for a good way of finding out if a ajax request is being performed on my page...now ive had a look about and found these two snippets.

 

Both seems to work fine...any suggestions on what one is best to use or even if there is a better way to do this would be helpful...thank you

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === "xmlhttprequest")
{
// is ajax 
}

if (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false){
// is ajax
}
Link to comment
Share on other sites

The first approach is nonsense. Whether or not the request was triggered by the XMLHTTPRequest interface is completely irrelevant. Will you send a different response or refuse to respond if you somehow find out that the client actually used a different technique? Will you rename the flag when there's some new client API? Why should you? It's always the same HTTP request, and it's always the same JSON data. The (supposed) origin of the request is as unimportant as the user's hair color or their sexual preferences.

 

The point is that the client asks for a JSON representation of the resource. And that's exactly what the second approach expresses: It tells the server to deliver JSON (rather than HTML, XML or whatever). This actually makes sense.

 

Of course both approaches technically work. You might as well use a X_I_LIKE_TURTLES header, the webserver doesn't give a damn. But if you want your application to make sense now and in the future, only the second solution is valid.

Link to comment
Share on other sites

well my approach was to stop people accessing the page the json data is on unless it is a actual json request

Any particular reason for that?

 

...was gonna put a script also which ensures the data is only gathered from my domain so its not local

Not really possible: the only thing available to you is the HTTP_REFERER and that can be spoofed very easily.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.