I can't find a way to load an image before getting my data. Practiclly what I want to do is:
- click a button
- display a loading image
- after 2 second the loading image should disapear
- after the image is out display my text
This is my code. I change it so many times that i don't know if is still good
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="libreria/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[name=campo1]").click(function(){
function imagen(){
$("#imagen").css("display", "block") ;
setTimeout(imagen, 2000);
}
var ajax = $.ajax({
type: "GET",
url : 'datos.txt',
/*beforeSend: function(){
});*/
});
ajax.done(function(data){
$("div").html(data);
});
ajax.fail(function(data){
alert("No se ha podido cargar el archivo");
});
});
});
</script>
</head>
<body>
<div>
<img id="imagen" src="images/loader.gif" style="display:none">
</div>
<input type="button" name="campo1" value="Traer fichero de texto"/>
</body>
</html>
Best Solution
By doing this, your loader image will show before you make your ajax call and disapear once completed. If en error has occured eg. the call fails: an alert is shown!
EDIT If you really want the loading pic to disapear after 2 secounds you could remove all
$("#imagen").hide()
, and paste this after$("#imagen").show()
. But i would disencurage you from doing that since the ajax request could take considerably longer time then that!One additional problem, that probably may be One of your conserns is that you are replacing the image with the loaded content. Since the image is in the same div that you place your data into. Try using
$("div").append(data)
instead of.html(data)
Or move your image outside the div.