How to find out if a request is an ajax request?

12,982

Solution 1

There's no 100% way to detect if the request was made via ajax. Even if someone sends header with "X-Requested-With: XMLHttpRequest" you shouldn't rely on it.

Solution 2

Not all browsers will send that response I usually use

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {//Do stuff }

and for ajax

request = $.ajax({
    url: SomePage.php,
    type: "POST",
    data: {key: value}
});
request.done(function(returnedData) {
    //do done stuff
});
request.fail(function(jqXHR, textStatus) {
    //do fail stuff
});

Note:

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. 
(Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that 
PHP handles them as such). Also note that long arrays were removed since PHP 5.4.0 so 
$HTTP_SERVER_VARS doesn't exist anymore.

So var_dump($HTTP_SERVER_VARS); to see if its contained in there, also note that the $_SERVER is filled in by the webserver

Share:
12,982
Stephan Wagner
Author by

Stephan Wagner

When I'm not hopping around the globe, you'll most likely find me glued to my mac hunting down syntax errors. I hate syntax errors! I sometimes blog a little too: stephanwagner.me/Blog

Updated on June 04, 2022

Comments

  • Stephan Wagner
    Stephan Wagner almost 2 years

    I try to find out if a request to a PHP file is sent by ajax or not.

    I googled it and read a whole a bunch of articles that suggest following method:

    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {     
        echo 'This is an ajax request!';   
        exit;
    }
    echo 'This is not an ajax request!';
    

    But my server doesn't have this variable: Undefined index: HTTP_X_REQUESTED_WITH ...

    Thats how I make the ajax request:

    $.ajax({
        url: 'http://URL/test.php',
        complete: function(res) {
            console.log(res.responseText);
        }
    });
    

    I'm making that call from a different url, so I've set header('Access-Control-Allow-Origin: *');

    I have discovered one difference in $_SERVER though:

    Ajax request: $_SERVER[HTTP_ACCEPT] => */*

    No Ajax request: $_SERVER[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

    So my question is, is there a way for me to get HTTP_X_REQUESTED_WITH into $_SERVER? And if not, is there a proper way to find out if the request is AJAX by using the $_SERVER[HTTP_ACCEPT]