Reputation: 4062
I am trying to convert the Owl Carousel to hold data pulled from a database. Using a button:
<button onclick="addCarousel('2015-06-11')">Test</button>
I call an AJAX function (the date is irrelevant for now):
function addCarousel(date){
date = new Date(date);
$.post("php/addCarousel.php", {date : date}, function(data){
$('#ajaxResponse').html(data);
});
}:
which pulls data using PHP (static script for now):
Echo
'<div id="owl-demo" class="owl-carousel">
<div class="scrollDay"><h1>0</h1></div>
<div class="scrollDay"><h1>1</h1></div>
<div class="scrollDay"><h1>2</h1></div>
<div class="scrollDay"><h1>3</h1></div>
<div class="scrollDay"><h1>4</h1></div>
<div class="scrollDay"><h1>5</h1></div>
<div class="scrollDay"><h1>6</h1></div>
<div class="scrollDay"><h1>7</h1></div>
<div class="scrollDay"><h1>8</h1></div>
<div class="scrollDay"><h1>9</h1></div>
<div class="scrollDay"><h1>10</h1></div>
<div class="scrollDay"><h1>11</h1></div>
<div class="scrollDay"><h1>12</h1></div>
<div class="scrollDay"><h1>13</h1></div>
<div class="scrollDay"><h1>14</h1></div>
<div class="scrollDay"><h1>15</h1></div>
</div>';
Which populates on my index page
<div id="ajaxResponse">
Data will go here
</div>
If I insert the elements into the index page directly then the carousel works fine, but it does not work when I generate it through php. My developer tools show that these elements exist on the page and there are no console errors, but the elements do not shown for some reason. I manually display: block;
for all elements, but that's not the issue.
I think that I need to re-instantiate the code, but I'm not sure how and where to do that. I've looked into these articles How to reinitialize Owl Carousel after ajax call, Owl carousel not displayed, and Call the plugin. I've tried to instantiate in a number of way, but this is a bit foreign to me.
The instantiation below works fine when the elements are added directly to the index page
$(document).ready(function() {
var owl = $("#owl-demo"),
status = $("#owlStatus");
owl.owlCarousel({
navigation : true,
afterAction : afterAction
});
function updateResult(pos,value){
status.find(pos).find(".result").text(value);
}
function afterAction(){
updateResult(".owlItems", this.owl.owlItems.length);
updateResult(".currentItem", this.owl.currentItem);
updateResult(".prevItem", this.prevItem);
updateResult(".visibleItems", this.owl.visibleItems);
updateResult(".dragDirection", this.owl.dragDirection);
}
});
How and where do I re-instantiate after the PHP runs?
Upvotes: 0
Views: 1098
Reputation: 641
You should restart carousel (re-instantiate) in Ajax call. After then, when new elements are added to the page
function addCarousel(date){
date = new Date(date);
$.post("php/addCarousel.php", {date : date}, function(data){
$('#ajaxResponse').html(data);
$("#owl-demo").owlCarousel();
});
}
Upvotes: 1