简体   繁体   中英

How do i pause javascript script until xhr request is done?

I have made a script that allows the user to send a weekly newsletter powered by php. My php code is fine and working 100%. However, i made a script to count how many newsletters have been send out to check if all the newsletters have been send.

The code i made is the following:

function sendMail(test) {
var onderwerp = document.getElementById('getOnderwerp').value;
var pin = document.getElementById('secretPIN').value;
var e = document.getElementById('selectBrief');
var brief = e[e.selectedIndex].value;
var checkbox = [];
$('input[type="checkbox"][name="check_list[]"]').each(function(_, ele) {
if ($(ele).prop('checked')) {
   checkbox.push($(ele).attr('value'));
  }
});
loadgif2();

var breakx = false;
var temp = '';
var text = '';
var h = 0;
var regExp = /\(([^)]+)\)/;
var xhr = [];

for(var j = 0; j < checkbox.length; j++) {

    if (breakx == true) {
        removegif();
        break;
    }


    var provincie = checkbox[j].replace(/\(([^)]+)\)/, '');
    var aantal = checkbox[j].match(regExp)[1];

    h = 0;

    xhr = [];

    temp = '';
    temp = provincie + ' word verstuurd';
    text += temp + '<br>';


    for (i = 0; i < aantal; i++) {
        if (breakx == true) {
            break;
        }
        (function (i) {
            xhr[i] = new XMLHttpRequest();
            url = "/modules/pages/ajax/nieuwsbrief/send-mail.php?provincie=" + provincie +
                "&test=" + test + "&brief=" + brief + "&onderwerp=" + onderwerp + "&pin=" + pin + "&offset=" + i;
            xhr[i].open("POST", url, true);
            xhr[i].onreadystatechange = function () {
                if (xhr[i].readyState == 4 && xhr[i].status == 200) {



    document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
     document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
                        h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;

                    h++;
                    if (h == aantal) {
                        text = text.replace(temp, provincie + ' is verzonden<br>');
                        document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
                    } else {
                        document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
                        h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;
                    }

                    console.log(xhr[i].responseText);

                    if (xhr[i].responseText == '<br> Ongeldige PIN') {
                        breakx = true;
                    }

                }
            };
            xhr[i].send();
        })(i);
    }
}
}

The code above is working but the only problem i'm facing is that as soon as i have a checkbox array length > 1 it'll not work properly. My guess is that the loop is going too fast and the xhr request just takes a little more time to get the php file stuff. My question is here how am i going to fix this? I was thinking myself to pause the script until the xhr requrest was done and resume it after.

Edit

I have edited my code to be like this:

    function sendMail(FormElements, test) {
    var onderwerp = document.getElementById('getOnderwerp').value;
    var pin = document.getElementById('secretPIN').value;
    var e = document.getElementById('selectBrief');
    var brief = e[e.selectedIndex].value;
    var checkbox = [];
    $('input[type="checkbox"][name="check_list[]"]').each(function(_, ele) {
    if ($(ele).prop('checked')) {
       checkbox.push($(ele).attr('value'));
      }
});
loadgif2();

    sendmail2(0, test,brief,onderwerp,pin,checkbox, '');
}

function sendmail2(checkboxcount, test,brief,onderwerp,pin,checkbox,text) {
    var breakx = false;
    var temp = '';
    var h = 0;
    var regExp = /\(([^)]+)\)/;
    var xhr = [];
    var provincie = checkbox[checkboxcount].replace(/\(([^)]+)\)/, '');
    var aantal = checkbox[checkboxcount].match(regExp)[1];

    temp = provincie + ' word verstuurd';
    text += temp + '<br>';
    for (i = 0; i < aantal; i++) {
        if (breakx == true) {
            break;
        }
        (function (i) {
            xhr[i] = new XMLHttpRequest();
            url = "/modules/pages/ajax/nieuwsbrief/send-mail.php?provincie=" + provincie +
                "&test=" + test + "&brief=" + brief + "&onderwerp=" + onderwerp + "&pin=" + pin + "&offset=" + i;
            xhr[i].open("POST", url, true);
            xhr[i].onreadystatechange = function () {
                if (xhr[i].readyState == 4 && xhr[i].status == 200) {
                    document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
                    document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
                        h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;

                    h++;
                    if (h == aantal) {
                        text = text.replace(temp, provincie + ' is verzonden<br>');
                        document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text;
                        if (checkboxcount + 1 == checkbox.length) {

                        } else {
                            sendmail2(checkboxcount + 1, test, brief, onderwerp, pin, checkbox,text);
                        }
                    } else {
                        document.getElementById("spancontent").innerHTML = 'Even geduld, nieuwsbrief word verzonden<br><br>' + text + '<br>' +
                            h + ' e-mails van de ' + aantal + ' verzonden in provincie ' + provincie;
                    }

                    console.log(xhr[i].responseText);

                    if (xhr[i].responseText == '<br> Ongeldige PIN') {
                        breakx = true;
                    }

                }
            };
            xhr[i].send();
        })(i);


    }
    }

This code acutally works the way i want to, but now i'm gettting some random 500 internal errors, but they seem to be completely random? sometimes they appear and sometimes they don't and i'm not changing anything. any solutions to this?

At your code:

xhr[i].open("POST", url, true);

Change it to:

xhr[i].open("POST", url, false);

It is a deprecated and bad workaround for your problem, you should find an other way. ( https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests )

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