GePraxa GePraxa - 1 month ago 7
Ajax Question

Show and Hide an element (status bar) when Ajax request starts and finishes

I have a form to upload photos via Ajax, the status bar appears when you start the request and is working properly. The problem is that when the request is over, the bar remains active and thumbnail photo appears. The bar should reappear if another request is made.

I would like to hide the bar when the request is finished, and tried several things but none of them worked, this is my code:

//jQuery Ajax to Post form data
$.ajax({
url : post_url,
type: "POST",
data : form_data,
contentType: false,
cache: false,
processData:false,
xhr: function(){
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
$(progress_bar_id + " .progress-bar").css("width", + percent +"%");
$(progress_bar_id + " .status").text(percent +"%");
}, true);
}
return xhr;
},
mimeType:"multipart/form-data"
}).done(function(res){ //
$(my_form_id)[0].reset(); //reset form
$(result_output).html(res); //output response from server
submit_btn.val("Enviar").prop( "disabled", false); //enable submit button once ajax is done
});


This is the HTML code to display the progress bar:

<div id="progress-wrp">
<div class="progress-bar"></div>
</div>

Answer

What did you try? Did you try a hide() at the bottom of your done() method? (this also show()s it when the request is made)

$("#progress-wrp").show(); gets the element by it's id using jquery and shows it (in this case when the request is starts).

$("#progress-wrp").hide(); gets the element by it's id using jquery and hides it (in this case when the request is done()).

xhr: function(){
     //upload Progress
     $("#progress-wrp").show();
     var xhr = $.ajaxSettings.xhr();
     if (xhr.upload) {
      xhr.upload.addEventListener('progress', function(event) {
       var percent = 0;
       var position = event.loaded || event.position;
       var total = event.total;
       if (event.lengthComputable) {
        percent = Math.ceil(position / total * 100);
       }
       //update progressbar
       $(progress_bar_id + " .progress-bar").css("width", + percent +"%");
       $(progress_bar_id + " .status").text(percent +"%");
      }, true);
     }
     return xhr;
    },
    mimeType:"multipart/form-data"

    .done(function(res){ //
        $(my_form_id)[0].reset(); //reset form
        $(result_output).html(res); //output response from server
        submit_btn.val("Enviar").prop( "disabled", false); //enable submit button once ajax is done
       $("#progress-wrp").hide();
       });
Comments