Skip to content Skip to sidebar Skip to footer

How To Wait For All Xhr2 Send Calls To Finish

I have done some code to upload multiple files from browser to server, while showing progressbars as well. XHR2 send calls are asynchronous. The problem is that I want to call some

Solution 1:

Do you know how many calls you are making? If so, at least ajax callback, you check the count. Something like

if (ajaxCallCount === ajaxCallsLength) {
 // Do stuff involving post all ajax calls
} else {
 ajaxCallCount++;
}

Solution 2:

You will need a counter and setInterval method in your case, try this:

<inputid="upload"multiple="multiple" /><script>var files = document.getElementById("upload").files;
var counter = 0;

for (var i = 0, length = files.length; i < length; i++) {
   var file = files[i];
   var uploadFunc = function (arg) {
      returnfunction () {
         processXHR(arg);
      };
   }(file);      
   uploadFunc();
}

var interval = setInterval(function() {
    if(counter == files.length) {
        clearInterval(interval);
        console.log("All Files uploaded!");
    }
}, 100);

functionprocessXHR(file) {
   var normalizedFileName = getNormalizedName(file.name);
   var url = 'upload_file/';
   var formData = newFormData();
   formData.append("docfile", file);
   var xhr = newXMLHttpRequest();
   var eventSource = xhr.upload;
   eventSource.addEventListener("progress", function (evt) {
      var position = evt.position || evt.loaded;
      var total = evt.totalSize || evt.total;
      console.log('progress_' + normalizedFileName);
      console.log(total + ":" + position);
      $('#progress_' + normalizedFileName).css('width', (position * 100 / total).toString() + '%');
   }, false);
   eventSource.addEventListener("loadstart", function (evt) {
      console.log('loadstart');
   }, false);
   eventSource.addEventListener("abort", function (evt) {
      console.log('abort');
   }, false);
   eventSource.addEventListener("error", function (evt) {
      console.log('error');
   }, false);
   eventSource.addEventListener("timeout", function (evt) {
      console.log('timeout');
   }, false);
   xhr.onreadystatechange = function (evt) {
      if (xhr.readyState == 4) {
         counter += 1;
      }
   };
    xhr.open('post', url, true);
    xhr.send(formData);
}
</script>

Post a Comment for "How To Wait For All Xhr2 Send Calls To Finish"