How do stop an alert from showing more than once on repeated calls to a function via AJAX?

StackOverflow https://stackoverflow.com/questions/23455844

Вопрос

Ok, I have this function below that I am calling every 5 seconds..

function checkVerfToken(user_id) {

    // Set file to get results from..
    var loadUrl = "ajax_files/check_verf_token.php";

    // Set parameters
    var dataObject = { user_id: user_id };

    // Run request

    getAjaxData(loadUrl, dataObject, 'POST', 'html')

        .done(function(response) {

            if (response == 'success') {
                // Reload the page
                window.location.replace('payment_completed_verf.php');
            }

        })

        .fail(function() {
            alert('There seems to have been a problem with continuing the verification process; please contact us if this continues to occur.');
        });

    // End       

}

I am calling it from a page every 5 seconds with:

<script type="text/javascript">
    window.setInterval(function(){
      checkVerfToken(<?=$user_id?>);
    }, 5000);
</script>

However if fail is executed then it obviously keeps doing it every 5 seconds as it doesn't leave the page.

How can I get it to just show the alert once if there is a problem?

Это было полезно?

Решение

Keep a reference to the interval, and clear it when it fails.

verifyInterval = window.setInterval(function(){
    checkVerfToken(<?=$user_id?>);
}, 5000);

.fail(function() {
    clearInterval(verifyInterval);
    alert('There seems to have been a problem with continuing the verification process; please contact us if this continues to occur.');
});

Другие советы

Not sure if this is the best way, but creating a dom element on the fly and checking for its existence will work, you can even check for its value and change them for any other action; so basically it acts as a flag and if required can be a conditional checker for other event firing:

.fail(function() {
    // create a hidden element in dom to check for the alert event execution
    if ($('#errorchecker').length === 0) {
        $('body').append('<input type="hidden" id="errorchecker" value="executed" />');
        alert('There seems to have been a problem with continuing the verification process; please contact us if this continues to occur.');
    }        
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top