I have a gif that in theory should be shown before the ajax request is made and should be hidden when this request has been resolved. This is how I have it programmed (according to my logic) but for some reason it is not shown when the onchange event starts, or at least that is not the experience it gives the user, it is shown almost almost when the request is resolved and immediately returns it to hide, but in the browser it is clearly seen that the screen stays as if thinking and since it is resolved it shows the gif and immediately hides it again.
This is my js code:
$("input[type=file]").on("change", function(){
$(".gif").show();
var fd = new FormData(document.querySelector("form"));
$.ajax({
url: "CargaArchivo.action",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false , // tell jQuery not to set contentType
success: function(response) {
//alert(response);
$('.gif').hide();
}
});
});
html:
<div id="contenidoAjax" class="gif">
<img class="img" src="/Imagenes/cargandoPaginaWeb.gif" width="40%;"/>
</div>
<input id="file" type="file" name="files" tag-estatus="0" tag-nombre="unNombreCualquiera"/>
EDIT: It seems that I have not given much to understand, I apologize; with "I have a gif that in theory should be displayed before the aja request is made" is literally that, before the ajax request is made, that is, as soon as the value of the input file is changed and before the request is made ajax. I have put my server to sleep and the "loading" looks very nice and everything, but it exits when the ajax request is being made, I want it to exit when the value of the input file is changed since if I start the "loading" when the ajax request is started the client screen is flashing for about 3 or 4 seconds before the ajax request is made (which are the ones I want to cover with the gif).
What is happening in those 3 or 4 seconds before the ajax request starts?
The hide should be done once the ajax has been completed, instead of in the onsuccess, because if the response is fast, even if it hasn't finished everything, it will try to hide it. Try this to see if you get the expected effect.
If not, another option is to associate it with the start and end of the ajax events.
If the version of jquery is from 1.9, the last part would be done like this:
Edit to run the image before
As it seems that it takes time to detect the onchange event, you can try adding an onclick function in the select tag that shows the gif (the click should be before the onchange), and then hide it when the ajax has been executed.
According to the documentation , the method
show
has 3 parameters:and the speed parameter has a default value of 400 milliseconds.
So it may be that when the method just finished executing the ajax request was already finished.
You can also bind the method to the start of the ajax request like this:
On the other hand, you can use a library called jquery-loading , easy to use and with customizable animations