Recently, I had a requirement where I had to show progress bar while I sent multiple files. I faced a problem since I had two forms, one contained files and the other had some input fields. Both forms were in modals and so it was not possible to submit them without ajax. One of the forms was in base outside body tag (this is required to blur the entire background as the form was in modal) and other form, in modal, without any associated file.
Please find solution to the above problem as below,
$.ajax({ type:POST, url : "your url", data : {dictionary}, enctype: 'multipart/form-data', cache: false, contentType: false, processData: false, xhr: function() { # xhr listener object $(".progress").show(); //here we show the progressbar myXhr = $.ajaxSettings.xhr(); #intialize xhr listner if(myXhr.upload){ # looks for upload data myXhr.upload.onprogress = function (e) {# calculate the data uploaded var completed = 0; if (e.lengthComputable) { var done = e.loaded,# gives estimate of how much data is uploaded total = e.total; # total size of data to be uploaded completed = Math.round((done / total * 1000) / 10); # this is where actual calculation takes place to show with of progressbar } var prog= Math.round(completed)+'%' # you can skip the round $(".progress-bar").width(prog); # value is set to progressbar } } return myXhr; }, success : function(response) { $(".progress-bar").width(0); $(".progress").hide(); }, error: function() { console.log('Error occured'); } });
Here, as you must have observed, I have used XHR object; this is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. This is the reason why it’s possible to use ajax. For more info regarding XHR please visit, http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp.