简体   繁体   中英

Jquery poll request only if variable != 'something'

I have this code:

<script>
    $(function() {
        (function poll(){
            setTimeout(function(){
                var process_id = $("#form3_progress_process_id").val();
                if(process_id != 'undefined') {
                    $.ajax({
                        type: "POST",
                        url: "grab.php",
                        data: "action=step3_progress&process_id=" + process_id,
                        success: function(data){
                            console.log("successful");
                        }, dataType: "json", complete: poll, timeout: 30000 });
                }
            }, 2000);
        })()
    });
</script>
<input type="hidden" id="form3_progress_process_id" value="undefined">

What i want is that it only sends the query if the value from the input form3_progress_process_id is not ' undefined '.

At the start it is " undefined " but after some time it get's changed with jquery.

However, the above code does not work for any reason. It does not start sending the request after the value has been changed.

What did i wrong?

Your code will fire only if the input changes in the first 2 seconds from the begining. You should add a call to the poll method in your else , so the cycle doesn't break:

$(function() {
    (function poll(){
        setTimeout(function(){
            var process_id = $("#form3_progress_process_id").val();
            if(process_id != 'undefined') {
                $.ajax({
                    type: "POST",
                    url: "grab.php",
                    data: "action=step3_progress&process_id=" + process_id,
                    success: function(data){
                        console.log("successful");
                    }, dataType: "json", complete: poll, timeout: 30000 });
            }else{
                poll();  ////Add this!!
            }
        }, 2000);
    })()
});

Cheers, from La Paz, Bolivia

Unless your hidden input changes within the 2 seconds, the timer will not fire again. change to setInterval

 setInterval(function(){
            var process_id = $("#form3_progress_process_id").val();
            if(process_id != 'undefined') {
                $.ajax({
                    type: "POST",
                    url: "grab.php",
                    data: "action=step3_progress&process_id=" + process_id,
                    success: function(data){
                        console.log("successful");
                    }, dataType: "json", complete: poll, timeout: 30000 });
            }
        }, 2000);
    })()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM