dgo
dgo

Reputation: 3937

jQuery.ajax loads image late?

I have a site that loads and injects html into a page for editing. The first thing I do when I load the html is that I check it for images and do some processing with them. It shouldn't require that they be all the way loaded - just their attributes - for me to process them.

There is literally one folder on the site where when I load html from that folder and get it back, it doesn't load the images properly. If I log the returned responseText, I can see the image as an element within. For example:

var ajax=$.ajax({
    url:url,       
    data:data,
    accepts:'html',
    dataType:'html',
    success:function(data){
      console.log($(data)) // -> logs jQuery HTML object to Chrome console w/ images
      console.log($(data).find('img')); // -> []
      window.d=$(data); // global object that I can parse in console and extract img
      });

The following gives the same problem:

    var ajax=$.ajax({
      url:url,
      data:data,
      accepts:'html',
      dataType:'html'
     });

     ajax.then(function(data){
      console.log($(data)) // -> logs jQuery HTML object to Chrome console
      console.log($(data).find('img').toArray()); // -> returns []
      window.d=$(data); // global object that I can parse in console and extract img
     });

The processing I do on the images isn't complicated. I just parse their source and store it in a global object.

How can this possibly be?

EDIT: I altered it a little bit to more accurately reflect the case. Also, keep in mind that this particular ajax call works in all other cases accept this on folder (maybe five diff. html files) : so I would imagine the error is in some way derived from something to do with the way the image loads ? That just doesn't make any sense though.

EDIT 2: Per request, here is an example of html returned when the errors occur. As you can see on the second line, there is an img:

<h2>About Frank A. ..., M.D.</h2>
<img class="fltleft" width="200" height="243" alt="Dr. ..." src="http://zjq.metapsychology.org/imgs/research_pub/img1.jpg">
<br>
<p>... is an Honors graduate of Stanford University who later pursued graduate studies in philosophy at Cambridge University in England. He received his medical degree from yale University, and completed a psychiatric residency at Stanford University Medical Center in the early 1970s.  ....</p>

I abbreviated the output. But there is an image there.

Upvotes: 0

Views: 211

Answers (1)

Kevin B
Kevin B

Reputation: 95022

Your images aren't descendants of the root element within data, they ARE root elements in data. use filter instead.

console.log($(data).filter('img'));

and to find both root AND descendants so it'l work in both cases, use this:

console.log($(data).find('img').addBack().filter('img'));
// find all images in data, add back the root elements, then filter to only images.

Upvotes: 1

Related Questions