Tips & Tricks

Detect an Ajax Request with PHP

In this quick tip article we will see how we can detect AJAX request using PHP.

This trick will be very useful and handy when you want the same request to behave differently for AJAX request and normal request.

Generally we used to echo the content or some sort of flag when we deal with AJAX and in normal request execution continue to serve HTML.

So Let’s see how we can detect weather request is made using AJAX or it’s a normal request.

[cc lang=”php”]
$ajax = false;

if(!empty($_SERVER[‘HTTP_X_REQUESTED_WITH’])
&& strtolower($_SERVER[‘HTTP_X_REQUESTED_WITH’]) == ‘xmlhttprequest’)
{
$ajax = true;
}
[/cc]

PHP’s $_SERVER[‘HTTP_X_REQUESTED_WITH’] variable is one strong sign that an AJAX request has been made from browser.

Hope you find this helpful for your work.

Shares:
  • Anna Harris
    Anna Harris
    January 21, 2013 at 5:31 pm

    Thanks for sharing code it helps me a lot.

    Reply
  • Toms
    Toms
    January 27, 2013 at 8:19 pm

    or as the one-line-code:
    [cc lang=”php”]
    $ajax = isset($_SERVER[‘HTTP_X_REQUESTED_WITH’]) && strtolower($_SERVER[‘HTTP_X_REQUESTED_WITH’]) == ‘xmlhttprequest’)
    [/cc]

    Reply
  • MM
    MM
    February 12, 2013 at 8:22 am

    Small, Easy and Effective code snippet… thanks for sharing..

    Reply
  • danik
    danik
    February 12, 2013 at 2:20 pm

    Why should we lowercase the header value ? Why not just [cc lang=”php”]$_SERVER[‘HTTP_X_REQUESTED_WITH’] == ‘XMLHttpRequest'[/cc]

    Reply
  • Dennis Gruetter
    Dennis Gruetter
    November 18, 2013 at 8:01 pm

    I was very sold on this solution but over the weekend I just found out that ie8 does not send this header. This turned out to be a deal breaker for me. Otherwise great solution.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *