A little dab'll do ya
Code Snippets
Detect AJAX Request
The HTTP_X_REQUESTED_WITH header is sent by all recent browsers that support AJAX requests.
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
# Ex. check the query and serve requested data
}
I think isset() is more appropriate than !empty() in this situation. Still a useful snippet though. :)
So that you don’t get the notice about whether the variable is set or the attribute is set you should use both isset() and !empty().
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'] && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
# Ex. check the query and serve requested data
}
You’re missing the close parenthesis on the isset, teehee.
*syntax whore*
great and practical snip, however, I’d like to know if there is a great or important disadvantage in using this approach when working with synchronized(normal request) and asynchronized(ajax request) requests in the same page.
The statement “The HTTP_X_REQUESTED_WITH header is sent by all recent browsers that support AJAX requests.” is 100% false.
The browser does not send this header, javascript libraries do. Libraries like jquery, prototype and mootools.