I'm using Laravel. What I'm trying to do is to insert some divs to .content
Bassically I select some data from database and insert using javascript in .content
I'm using owl carousel for sliding images.
The problem is that, the owl carousel is called before I select the data and inner to .content and its display none because there is no .item-images at the time the owl carousel is loaded.
The question, is how can I make to fix this?
I've tested with adding a timeout to owl carousel for 5 seconds and is working, but when you visit the site there is a little deelay when images appear (of course because of 5 sec timeout) and I don't want users to experience that.
index.blade.php
<div class="content">
<div class="list" id="list">
</div>
</div>
app.js
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(() => {
var owl2 = $('.item-images').owlCarousel({
items: 1,
dots: true,
nav: true,
loop: false,
autoplay: false,
mouseDrag: false,
smartSpeed: 500
});
})
$.ajax({
url: 'api/getItemsFromDb',
type: "POST",
data: {
user: '1'
},
success: function (c)
{
innerItemsToContent(c);
},
error: function(e)
{
console.log(e);
}
});
function innerItemsToContent(item)
{
var container = document.getElementById("list");
if(container)
{
item.forEach(e => {
container.innerHTML += `
<div class="item">
<div class="title">${e.title}</div>
<div class="message">${e.message}</div>
<div class="item-images owl-carousel" id="img_insert"></div>
</div>
`;
var container_img = document.getElementById("img_insert");
for(var i = 0; i < e.count_pictures; i++)
{
console.log('test');
container_img.innerHTML += `
<img src="assets/tools/img_posts_test/${e.img[i].img_laravel_name}.${e.img[i].img_type}" name="${e.id} item id" class="img-item-style">
`;
}
});
}
}
API.php (Controller)
public function getItemsFromDb(Request $r)
{
$r->validate([
'user' => 'required'
]);
$data = DB::table('items')->where('item_id', '=', 1)->orderBy('id', 'asc')->limit(1)->get();
$img = DB::table('images')->where('belongs_to_item', '=', 1)->orderBy('id', 'asc')->get();
foreach($data as $d)
{
if($d->count_pictures > 0)
{
$count = 0;
foreach($img as $i)
{
$d->img[$count] = $i;
$count++;
}
}
}
return $data;
}