Code Snippet
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.
Hi guys,
I want to check availability of internet connection before every AJAX request. If the connection is available – proceed else give a pop up message- net not available.
I wrote the javascript to check net connection.But to check if a request is a AJAX request or a normal request if put following filter in my javaScript code:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'] && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’))
I got following error
$_SERVER is not defined
Can anyone correct me, if I am going wrong.
@Suresh, that’s PHP code you’re trying to run inside of JavaScript. $_SERVER is only available to PHP so you’re getting ‘undefined’
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.