I have a page with a carousel which will send an ajax request each time a slide has changed, and will generate products related the slide into another carousel at the bottom.
At the moment when each slide has changed, the products are successfully drawn with Ajax, though I need to initiate the slider with the products once the ajax request has loaded. Right now the slider tries to initialize before the requests have finished.
On the bottom of the code I added, the each function adds each of the getProducts function to an array and then when it is done, it should initialize the slider. Though in the console the message 'this is initialized' happens before the 'success' messages in the Ajax request.
Have I used the deferred wrong in this example to cause this problem?
var products = [],
uniqueProducts = [],
defs = [];
var el;
$('.your-class [data-slick-index="' + currentSlide + '"] a').each(function(i) {
el = $(this).attr("href");
products.push(el);
$.each(products, function(j, el) {
if ($.inArray(el, uniqueProducts) === -1)
uniqueProducts.push(el);
console.log("pushed" + uniqueProducts);
});
});
function getProducts(el) {
var def = new $.Deferred();
var url = el;
$.get(url, function(data) {
var imageArray = data.match(/<img itemprop="image" [\S\s]*?>/ig);
var $image = $(imageArray[0]);
var imageUrl = $image.attr('src');
var name = $image.attr('title');
var priceArray = data.match(/<p class="price">[\S\s]*?<\/p>/ig);
var priceEl = $(priceArray[0]).find('[itemprop=price]');
priceEl.children().remove();
var price = priceEl.text() ? '$' + priceEl.text() : '';
$( ".carousel2" ).append( '<div><img src=\" '+ imageUrl +'\"></div>');
console.log("success");
def.resolve();
});
return def.promise();
}
$.each(uniqueProducts, function(i, el) {
defs.push(getProducts(el));
});
$.when($,defs).done(function () {
$('.carousel2').slick({ speed: 500, autoplay: false, autoplaySpeed: 4000, arrows:false });
console.log("this is initialized");
});
}