I am trying to reinitialize owl carousel after a successful ajax call. The ajax call will change the data but the view should stay the same.I am having an issue where the view carousel structure will not reinitialize. I don't know where I did mistake.
Ajax Request
$(document).on('click', '.category_list', function() {
var category_id = $(this).attr('data-id');
var _token = $('#_token').val();
var param = 'category_id=' + category_id + '&_token=' + _token;
$.ajax({
type: "POST",
datatype: "json",
url: "/master/sub_category",
data: param,
success: function(result) {
$('#test').html(result);
var owl = $(".owl-carousel");
owl.owlCarousel({
items: 4,
navigation: true
});
}
});
});
Controller Function
public function getImg() {
$post_data = Request::all();
$sub_img = $this->imgModel->getImgList($post_data);
$sub_img_html = '';
foreach ($sub_img ['data'] as $data_img ) {
$img = '/img/sub_category/'.$data_img ['img'];
$sub_img_html .= '<div class="item">';
$sub_img_html .= '<img src="'.$img.'" />';
$sub_img_html .= '</div>';
}
echo $sub_img_html;
}
View
<div id="demo">
<div id="test" class="owl-carousel">
<?php
if (!empty($img_category)) {
foreach ($img_category as $imgcategory){
?>
<div class="item">
<img src='/img/sub_category/<?= imgcategory['subcategory_img'] ?>'/></div>
<?php
}
}
?>
</div>
</div>
As per your code I make changes please apply this I hope this code work full.
success: function(result) {
$('#demo').html('<div id="testing" class="owl-carousel"></div>');
for(var i=0;i<result.length;i++){
$(".owl-carousel").append('<div class="item"><img src="/img/sub_category/'+result[i].subcategory_img+'" /></div>');
};
var owl = $("#testing");
owl.owlCarousel({
items: 4,
navigation: true
});
I believe you will need to destroy and re-initalize the carousel. There is a destroy method you can call;
https://github.com/OwlCarousel2/OwlCarousel2/blob/develop/src/js/owl.carousel.js#L1391
or there is a refresh method;
https://github.com/OwlCarousel2/OwlCarousel2/blob/develop/src/js/owl.carousel.js#L608
or there is an update method;
https://github.com/OwlCarousel2/OwlCarousel2/blob/develop/src/js/owl.carousel.js#L569
I believe these can all be called;
$('.owl-gallery').owlCarousel('refresh');
Might be worth a try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With