How to wait for an image to be loaded from ajax () success data?

I have a jquery ajax() function:

 $.ajax({ type: "POST", url: 'ajax.php', data: 'url='+variable, success: function(data){ $('#mydiv').html(data); } }); 

My ajax ( data variable) answer is similar to this:

 <a id="90" href="mylink"><img src="myimagelink90.jpg" /></a> <a id="91" href="mylink"><img src="myimagelink91.jpg" /></a> <a id="92" href="mylink"><img src="myimagelink92.jpg" /></a> <a id="93" href="mylink"><img src="myimagelink93.jpg" /></a> <a id="94" href="mylink"><img src="myimagelink94.jpg" /></a> <a id="97" href="mylink"><img src="myimagelink97.jpg" /></a> <a id="98" href="mylink"><img src="myimagelink98.jpg" /></a> <a id="120" href="mylink"><img src="myimagelink120.jpg" /></a> <a id="121" href="mylink"><img src="myimagelink121.jpg" /></a> <a id="122" href="mylink"><img src="myimagelink122.jpg" /></a> <a id="123" href="mylink"><img src="myimagelink123.jpg" /></a> <a id="124" href="mylink"><img src="myimagelink124.jpg" /></a> <a id="125" href="mylink"><img src="myimagelink125.jpg" /></a> 

So my question is: what is the easiest way to wait for myimagelink # .jpg loaded?

+4
source share
4 answers

Try using the load() function. In this case, you need to bind it using the live() handler, as the images are dynamically loaded:

 var loaded = 0; $('#mydiv a img').live('load', function() { loaded++; if (loaded == $('#mydiv a img').length) { alert('All of the images have loaded.'); } }); 

There may be a more efficient way to do this, so feel free to say how slowly it can work.

+5
source

You will need to place the "onload" event on each, increment the counter and see if it matches the number of images inserted.

+1
source

Do you upload images dynamically and want to display them after upload?

As long as "data" is a javascript variable containing strings, your images will not load ...

To load images before embedding them on the page, you will need to make them dom elements.

I don't know if this is the best option, but I think this works:

 $.ajax({ type: "POST", url: 'ajax.php', data: 'url='+variable, success: function(data){ $('<div />').html(data).load(function(){ $(this).appendTo("#myDiv"); }) }); 
+1
source

Sort of:

 $.ajax({ type:"POST", url: "ajax.php", dataType: "application/x-www-form-urlencoded", data: "url=" + variable, async: true, beforeSend : function(){ $("#Loading").show(); //show image loading }, success: function(msg){ $("#LoadingPiloto").hide(); //hide image loading } }) 
+1
source

Source: https://habr.com/ru/post/1347620/


All Articles