Search code examples
phpjqueryajaxbioinformaticslong-polling

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.


Solution

  • 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"