0

I need to preload ajax data before attaching it to a div and for that I have this code:

$.ajax({ 
   url: 'ajax.php',
   data: { modelID:id },
   type: 'post',
   success: function(result){

      $(result).load(function(){
         $('.view_'+id).html(result)
         $('.view_'+id).find('.brandModelGallery').bxSlider({})
         $('.view_'+id).addClass('loaded')
      })

   }
})

And this doesn't return anything. If write it as $('.view_'+id).load(result) then I can see all the contents of result in console as a syntax error so it fetches them alright, but not this way. Why is that?

Xeen
  • 6,955
  • 16
  • 60
  • 111

1 Answers1

0

I've create an example on jsfiddle

Html:

<div id="d1"></div>
<div id="d2"></div>

js:

$.ajax({ 
   url: './',
   data: { modelID: '1' },
   type: 'post',
   success: function(result){
     console.log(result);
     $('#d1').html(JSON.stringify(result));
     // A fake object as your result.
       var bxSlider =  $('<ul class="bxslider"><li><img src="https://i.imgur.com/KsV6jS5.png" /></li><li><img src="https://i.imgur.com/bqcK47I.png" /></li></ul>');       

       // Do thing only when all img loaded.
       var unLoadimges = bxSlider.find("img").length;
       bxSlider.find('img').load(function() {
           --unLoadimges;
           console.log("loaded, left: " + unLoadimges);
           if (unLoadimges === 0) {
               bxSlider.appendTo($("#d2")).bxSlider();
           }
       });
   }
})

When you append img element to your page, it doesn't mean its loaded. Listen to its load event.

Edit: Just make the bxSlider works on my example now. Not sure if there's a better way to check whether all images loaded or not.

fuyushimoya
  • 9,715
  • 3
  • 27
  • 34