Detect an Ajax Request with PHP

  • Avinash
  • 5
  • Jan 15, 2013
  • Tips & Tricks

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.

$ajax = false; if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $ajax = true; }
$ajax = false;

&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
  $ajax = true;

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.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by:

  • Anna Harris

    Thanks for sharing code it helps me a lot.

  • Toms

    or as the one-line-code:

    $ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
    $ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
  • MM

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

  • danik

    Why should we lowercase the header value ? Why not just

  • Dennis Gruetter

    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.