Penny Liu
Penny Liu

Reputation: 17388

Aborting AJAX request in long polling function

I'm implementing an application which can be able to monitor background jobs (BLAST program).

I wish that when PID equal 0, then stop the polling process.

But in my long-polling example, the polling process continues to run even use abort() function.

This solution is not working for me.

var poll_xhr;

    (function doPoll() {
        setTimeout(function() {
            poll_xhr = $.ajax({
                type: 'GET',
                url: 'longpoll.php',
                error: function (request, textStatus, errorThrown) {
                    displayError();
                },
                success: function(result) {
                    if (result == 0) {

                        // To kill the AJAX request (Not Working)
                        console.log("The process is not running.");
                        poll_xhr.abort();
                    }
                    else 
                        console.log(result);        
                },
                dataType: "json",
                complete: doPoll,
                timeout: 5000
            });
        })
    })();   

PHP CODE:

    $pid = $_SESSION['PID'];

    if(file_exists('/proc/'. $pid)){
        // $pid is running
        echo json_encode($pid);
    }
    else{ 
        $e = 0;
        echo json_encode($e); 
    }

How can I cancel the polling process? Any suggestions would be appreciated.

Upvotes: 1

Views: 718

Answers (2)

LeGEC
LeGEC

Reputation: 51780

calling doPoll on complete means it always will be called, whatever the result and the state of the xhr.

From your requirements, you should call doPoll from the successhandler, when the result says "job is still running"

Upvotes: 1

tansuo19
tansuo19

Reputation: 1

try to use "clearTimeout()" and don't use "complete".

var poll_xhr;

(function doPoll() {
    var time=setTimeout(function() {
        poll_xhr = $.ajax({
            type: 'GET',
            url: 'break.php',
            error: function (request, textStatus, errorThrown) {
                //displayError();
                console.log(request, textStatus, errorThrown);
            },
            success: function(result) {
                if (result == 0) {

                    // To kill the AJAX request (Not Working)
                    console.log("The process is not running.");
                    //poll_xhr.abort();
                    clearTimeout(time);
                }
                else {
                    console.log(result);   
                    doPoll     
                }
            },
            dataType: "json",
            //complete: doPoll,
            timeout: 5000
        });
    })
})(); 

Upvotes: 0

Related Questions