How to detect Ajax Request?

Asked

Viewed 1,997 times

13

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

  • 4

    http://davidwalsh.name/detect-ajax

  • 1

    A possibility would be you add a ? ajax=1 at the end of the URL in the call, so you wouldn’t need to depend on headers.

2 answers

13


Yes you have:

Code

<?php

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

With 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
}

6

For those interested, the solution below follows the same line of reasoning as that presented by Harry Potter, however, it has better performance, in order to 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 also worth noting that this type of verification depends on an information that despite being supported by the majority of frameworks may not be available after processing the Request, as is the case with old versions Dojo.

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

  1. Submit a GET/POST value identifiable by your application.
  2. 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 as it already does. The above fragment only demonstrates how to do it, in order to be able to send other custom headers, prefixed with X-

If you send the header manually you can further optimize the verification function without the need to verify the existence of the information, take into account the case of the string and etc. Just compare the value:

function isXmlHttpRequest() {

    return ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' );
}
  • 2

    Always good to know that there is maturity to negatively by the simple fact of being able to do it.

  • Someone denied your answer ?

  • Unfortunately, yes. Interestingly, if such a person has been negative, he has had some reason. If I wrote something wrong it is because I am human (still) then that she would show more wisdom and comment for me to correct (giving due credit) or even edit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.