Help to abort jQuery.ajax request, jQuery.post

Asked

Viewed 73 times

0

I use a php page to monitor new entries in the database for 30s and so far everything works fine, the problem is that I can’t leave the main page immediately, because it is waiting for the reply of the request and the end of the loop in php.

For what I researched I must use the . abort(); to abort the request, but I am having difficulties in its use, as it does not seem to work within the fail() function, which is called when I try to change page without the response of the request.

Basically I make the call on the main page:

<script type='text/javascript'>monitoramento('parametros');</script>

Send the request via Jquery.ajax (already tried with Jquery.post too) to the php page that will monitor the DB:

function monitoramento(parametros){
    var longp = $.ajax({
        type: "POST",
        url: "monitoramento-tags.php",
        data: { "parametro":parametros },
        //dataType: "dataType",
        success: function (resposta) {
            $("#usuarios").html(resposta);
        }
    });

    // Esse funciona
    //longp.abort();


    longp.fail(function(){
        alert('FECHAR')
        // Esse não funciona
        longp.abort();
    });
}

And the php page, which briefly monitors new records for 30s:

...
for($x=0; $x<30;$x++){

   // Realiza consulta no DB

   // Espera 1s antes da próxima consulta
   sleep(1);
}
...

In short: I want to leave the main page and browse the site, but the request made using jQuery.ajax is waiting for response from the php page, which can take up to 30s to happen, i.e., I click on a link and have to wait instead of aborting the request and immediately change page.

1 answer

0


After much research I ended up finding the solution, actually it has nothing to do with jQuery.ajax or jQuery.post and yes with the php page, because in it I use a session that ends up blocking the completion.

The solution is rather simple, although the identification of the problem is not so much. Finally, just use session_write_close() after the use of the session, being as follows:

// Abro a sessão
session_start();
...
// Manipulo a sessão, se necessário
...
// Finalizo o bloqueio e a manipulação da sessão
session_write_close();
...
// Continuo com o restante do código
...

Acknowledgement / Reference / Source: imasters Articles

Browser other questions tagged

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