0

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.

3
  • 2
    maybe 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. Commented Apr 30, 2014 at 11:14
  • @Bobby5193 if you would kindly post the comment as an answer, I'd be glad to accept it. Worked great. No idea why I didn't think of that. Commented Apr 30, 2014 at 11:18
  • ok, I did that just now :) Commented Apr 30, 2014 at 11:24

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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
    }

Comments

0

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.... */

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.