Eduard Luca
Eduard Luca

Reputation: 6602

How to detect if request is AJAX from JS

I have a messaging system for which I do infinite scroll using jQuery.load. The problem is that the way I set it up, when the response of jQuery.load returns, all JS from the page is ran once again. This is fine, but I want to disable a particular JS block only if the request is an AJAX (jQuery.load).

Is it possible to do something like this?

if(!request_is_ajax){
    run_some_code();
}
else{
    // do nothing
}

Basically the code should run on the main pageload, but not on subsequent calls. I can detect this server-side, but that would be the last resort for me.

Upvotes: 0

Views: 1037

Answers (4)

Bobby5193
Bobby5193

Reputation: 1625

You can set a global js variable to false once you loaded the code you want, and then check if it's true when the code executes again. I don't think a code snippet is really necessary here.

Upvotes: 1

KhorneHoly
KhorneHoly

Reputation: 4766

You can check in the Responseheader, because $.ajax will send an jqXHR(jQueryXMLHttpRequest).

The statement would be something like this:

    if( jqXHR.getResponseHeader('content-type').indexOf('text/html') >= 0 ) {
    ...
    }

For further information you can look up this stackoverflow answer

Upvotes: 0

Bud Damyanov
Bud Damyanov

Reputation: 31829

If you use jQuery, you can check $_SERVER['HTTP_X_REQUESTED_WITH'], which will be set to XMLHttpRequest. This is the most reliable method when using jQuery because the XMLHttpRequest is JavaScript object that makes the request. It's poorly named now, though, because you can have it send whatever you want.

Example code:

/* decide what the content should be up here .... */
$content = get_content(); //generic function;

/* AJAX check  */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    /* special ajax here */
    die($content);
}

/* not ajax, do more.... */

Upvotes: 0

Anup_Tripathi
Anup_Tripathi

Reputation: 2817

For the subsequent call (ie ajax call after page load) append something like ?ajax or &ajax and check the same on server side to know whether the request is an Ajax request or not.

// a server side php code sample
   $request_is_ajax= @$_GET['ajax']?true:false;
   if(!$request_is_ajax){
        run_some_code();
    }
    else{
        // do nothing
    }

Upvotes: 1

Related Questions