How to detect Ajax Request? [duplicate]

12

Is there any way in PHP to detect if the request is Ajax?

    
asked by anonymous 22.05.2014 / 15:52

2 answers

12

Yes you have:

Code

<?php

 if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
 *// FOI AJAX   
}

Function function

<?php

function isXmlHttpRequest()
{
    $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? $_SERVER['HTTP_X_REQUESTED_WITH'] : null;
    return (strtolower($isAjax) === 'xmlhttprequest');
}

if (isXmlHttpRequest()){
  // FOI AJAX
}
    
22.05.2014 / 15:56
5

For those interested, the solution below follows the same line of reasoning as that presented by Harry Potter, however, it has better performance, if you simply compare a value without the need to treat it:

function isXmlHttpRequest() {

    $header = ( array_key_exists( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ?
                  $_SERVER['HTTP_X_REQUESTED_WITH'] : '' );

    return ( strcmp( $header, 'xmlhttprequest' ) == 0 );
}

However, it is worth mentioning that this type of verification depends on information that although supported by the majority of frameworks may not be available after processing the Request, as is the case of href="http://trac.dojotoolkit.org/ticket/5801"> old versions Dojo.

If this is a problem for you, to have 100% guarantee, you have two options:

  • Send an identifiable GET / POST value for your application.
  • Manually send this Request Header . With jQuery, for example, it would look like this:

    $.ajax({
    
        type: 'POST', // Ou GET
        url: 'algum-arqiuvo.php',
    
        beforeSend: function( xhr ){
            xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
        }
    });
    
  •   

    There is no need to send this header manually with jQuery because it already does. The above fragment only demonstrates how to do it, since it is possible to send other custom headers prefixed with X -

    If you send the header manually you can further optimize the verification function without checking the existence of the information, taking into account the case of the string and so on. Just compare the value:

    function isXmlHttpRequest() {
    
        return ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' );
    }
    
        
    22.05.2014 / 19:26