0

i send ajax request every 5 second and i want wait for next requset until the previous one is done ... Because it sends a lot of requests even if the status of the previous request is pending, and this causes me a problem with the server.

this is my Java Script code : this is my Java Script code :

$(document).ready(function(e){


    $("#getUsersId").on('submit', function(e){
    e.preventDefault();
            $('.loading_spinner').css('display','flex');
            $('.form-fieldset.api-mode').attr('disabled','disabled');
let id = 1;
let zeroNum = "0";
var keyword = $('#keyword').val();
var region = $('#region').val();

// you can use a "fat-arrow" function or a function reference, look at the docs

let timer = 5000;

// console.log(timer);


const interval = setInterval(() => {

if (id>=9) {
    let zeroNum = "";
}
     $.ajax({
            type: "post",
            url: "dataExtractorRequset.php",
            data: {keyword: keyword,region: region,id:id},
            dataType: 'json',

            success: function (response) {
// var parsedJson= JSON.parse(response);
// console.log(response);
    function countTextArea() {
    var text = $("#FbUsersId").val();   
    var lines = text.split(/\r|\r\n|\n/);
    var count = lines.length-1;
    return count; 
    }

    var output2 = "";

                if(response.status == 1){
            clearInterval(interval);

$('.successMSG').html(Swal.fire({
  icon: 'success',
  title: response.message,
  showConfirmButton: true,
  timer: 3000,
  timerProgressBar: true
})
);

        $('.loading_spinner').css('display','none');
        $('.form-fieldset.api-mode').removeAttr('disabled');
        $('#sendForm').css('display','block');
            var arr = $("#FbUsersId").val().split("\n");

            var arrDistinct = new Array();
             $(arr).each(function(index, item) {
                 if ($.inArray(item, arrDistinct) == -1)
                    arrDistinct.push(item);
             });

             var newUniquData = arrDistinct;
             $.each(newUniquData, function(key, value) { 
               output2 += value+'\r\n';
                });  
             
            $("#FbUsersId").val(output2);
             $('#usersCount').html(countTextArea);
            var text = $('#FbUsersId').val();
            text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
            $(FbUsersId).val(text);

            console.log("success");
            console.log(arrDistinct);
            alert("Done !!!");

    }else{

    var output = "";
    for (i =0; i< response.length; i++) {
       console.log(response[i].data.user_url);
       output += response[i].data.user_url+ '\r\n';
    }

    // var appendData = $("#FbUsersId").val();
    // var newData = appendData + output;
    $("#FbUsersId").append(output);


    $('#usersCount').html("Loading...");


         if(response.status == 0) {

        $('.loading_spinner').css('display','none');
        $('.form-fieldset.api-mode').removeAttr('disabled');
clearInterval(interval);

$('.successMSG').html(Swal.fire({
  icon: 'error',
  title: response.message,
  text: response.errMSG,
  showConfirmButton: true,
  timer: 10000,
  timerProgressBarColor: '#435ebe',
  timerProgressBar: true
}).then(function(isConfirm) {
  if (isConfirm) {
    // location.reload();
  } else {
    //if no clicked => do something else
  }
})
);
}



    }

    },
    error: function(jqXHR, textStatus, errorThrown) {
       // console.log(textStatus, errorThrown);
    }
});



  id++;

  // stop the interval when id is greater 9
  // if (id > 9) {

  // }
}, timer); // 3000 is the time in milliseconds




});



});

How can I solve this problem.

  • Set a global flag when you send the AJAX request, and clear it when you get the response. Check the variable before making the next call. – Barmar Sep 23 '22 at 20:45

1 Answers1

0

Not so elegant (I would set setTimeout) but as Barmar suggested a global variable is quick solution:

$(document).ready(function (e) {


    $("#getUsersId").on('submit', function (e) {
        e.preventDefault();
        $('.loading_spinner').css('display', 'flex');
        $('.form-fieldset.api-mode').attr('disabled', 'disabled');
        let id = 1;
        let zeroNum = "0";
        var keyword = $('#keyword').val();
        var region = $('#region').val();

        // you can use a "fat-arrow" function or a function reference, look at the docs

        let timer = 10000;

        // console.log(timer);


        var in_progress
        const interval = setInterval(() => {

            if (in_progress) {
                return;
            }
            in_progress = true;
            if (id >= 9) {
                let zeroNum = "";
            }
            $.ajax({
                type: "post",
                url: "dataExtractorRequset.php",
                data: { keyword: keyword, region: region, id: id },
                dataType: 'json',

                success: function (response) {

                    in_progress = false;
                    // var parsedJson= JSON.parse(response);
                    // console.log(response);
                    function countTextArea() {
                        var text = $("#FbUsersId").val();
                        var lines = text.split(/\r|\r\n|\n/);
                        var count = lines.length - 1;
                        return count;
                    }

                    var output2 = "";

                    if (response.status == 1) {
                        clearInterval(interval);

                        $('.successMSG').html(Swal.fire({
                            icon: 'success',
                            title: response.message,
                            showConfirmButton: true,
                            timer: 3000,
                            timerProgressBar: true
                        })
                        );

                        $('.loading_spinner').css('display', 'none');
                        $('.form-fieldset.api-mode').removeAttr('disabled');
                        $('#sendForm').css('display', 'block');
                        var arr = $("#FbUsersId").val().split("\n");

                        var arrDistinct = new Array();
                        $(arr).each(function (index, item) {
                            if ($.inArray(item, arrDistinct) == -1)
                                arrDistinct.push(item);
                        });

                        var newUniquData = arrDistinct;
                        $.each(newUniquData, function (key, value) {
                            output2 += value + '\r\n';
                        });

                        $("#FbUsersId").val(output2);
                        $('#usersCount').html(countTextArea);
                        var text = $('#FbUsersId').val();
                        text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
                        $(FbUsersId).val(text);

                        console.log("success");
                        console.log(arrDistinct);
                        alert("Done !!!");

                    } else {

                        var output = "";
                        for (i = 0; i < response.length; i++) {
                            console.log(response[i].data.user_url);
                            output += response[i].data.user_url + '\r\n';
                        }

                        // var appendData = $("#FbUsersId").val();
                        // var newData = appendData + output;
                        $("#FbUsersId").append(output);


                        $('#usersCount').html("Loading...");


                        if (response.status == 0) {

                            $('.loading_spinner').css('display', 'none');
                            $('.form-fieldset.api-mode').removeAttr('disabled');
                            clearInterval(interval);

                            $('.successMSG').html(Swal.fire({
                                icon: 'error',
                                title: response.message,
                                text: response.errMSG,
                                showConfirmButton: true,
                                timer: 10000,
                                timerProgressBarColor: '#435ebe',
                                timerProgressBar: true
                            }).then(function (isConfirm) {
                                if (isConfirm) {
                                    // location.reload();
                                } else {
                                    //if no clicked => do something else
                                }
                            })
                            );
                        }

                    }

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // console.log(textStatus, errorThrown);
                    in_progress = false;
                }
            });

            id++;

            // stop the interval when id is greater 9
            // if (id > 9) {

            // }
        }, timer); // 3000 is the time in milliseconds

    });

});
IT goldman
  • 14,885
  • 2
  • 14
  • 28