A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Code Snippets > PHP > Detect AJAX Request Submit one!

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
}

Subscribe to The Thread

  1. Frank says:

    I think isset() is more appropriate than !empty() in this situation. Still a useful snippet though. :)

  2. David says:

    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
    }

  3. Dani says:

    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.

  4. SmarterGuy says:

    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.

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---