How to create bootstrap carousel with ajax call?

I’m trying to create a bootstrap carousel in Ajax call. Here I have a carousel in main page:

<!DOCTYPE html>
    <html lang="es">
        <head>
            <meta charset="UTF-8">
            <title>Carousel with ajax</title>
            <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
            <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> 
            <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
            <script type="text/javascript" src="js/ajaxCarousel.js"></script>
        </head>
        <body>
            <div class="container">
                <h2>Carousel with ajax</h2>
                <div class="row">
                    <!-- TRIGGER BOOTSTRAP CAROUSEL -->
                    <a href="image.php" class="modalImage" data-toggle="modal" data-var="images/image/">
                        <img class="img-fluid" src="image.png" alt="" style="width:20%">
                    </a>
                    <!-- BOOTSTRAP CAROUSEL -->
                    <div id="carousel" class="carousel slide" data-ride="carousel">
                        <!-- Indicators -->
                        <ol class="carousel-indicators"></ol>
                        <!-- Wrapper for slides -->
                        <div class="carousel-inner"></div>
                        <!-- Controls -->
                        <a class="carousel-control-prev" href="#demo" data-slide="prev">
                            <span class="carousel-control-prev-icon"></span>
                        </a>
                        <a class="carousel-control-next" href="#demo" data-slide="next">
                            <span class="carousel-control-next-icon"></span>
                        </a>
                    </div>
                    <!-- CLOSE BOOTSTRAP CAROUSEL -->
                </div>
            </div>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> 
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.bundle.min.js" integrity="sha384-zDnhMsjVZfS3hiP7oCBRmfjkQC4fzxVxFhBx8Hkz2aZX8gEvA/jsP3eXRCvzTofP" crossorigin="anonymous"></script> 
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>    
        </body>
</html>

From this page I go to image.php to search an image inside a folder:

<?php
header('Content-Type: application/json');
$directory = $_POST['var'];
echo json_encode (glob($directory. '*.{png,mp4}', GLOB_BRACE));
?>

Finally I make an Ajax call to show images in carousel. First I store data as an array with map function. Then I get access to the data with each function.

$(document).ready(function(){
    // ------------    TRIGGER CLICK EVENT    ------------
    $('.modalImage').click(function (event) {
        event.preventDefault();
        var data = this.dataset;
        // ------------    TRIGGER AJAX    ------------
        $.ajax({
            url: "image.php",
            data: data,
            type: "POST",
            dataType: "json",
            success: function(data) {
                // ------------    STORE SEVERAL IMAGES AS AN ARRAY WITH MAP FUNCTION    ------------  
                var imgs = data.map(function(img) {
                    var html = "";
                    var fileExtension = img.substring(img.lastIndexOf('.'));
                    if (fileExtension == ".png") {
                        return html += '<img src="'+img+'"></img>';
                    }
                });
                // ------------    ACCESSING ARRAY ELEMENTS WITH EACH FUNCTION IN CAROUSEL    -------------
                $.each (imgs, function(i,val) {
                    $('<div class="carousel-item"><img class="d-block img-fluid" src='  + i + '></div>').appendTo('.carousel-inner');
                    $('<li data-target="#carousel" data-slide-to="' + i + '"></li>').appendTo('.carousel-indicators');
                })
                // ------------    SHOW CAROUSEL    -------------
                $('#carousel').carousel();
                $('.carousel-indicators > li').first().addClass('active');
                $('.carousel-item').first().addClass('active');
                
            } 
        });
    });
});

Unfortunately the code does’t work and the page does’t indicate any warning or error. What could be wrong with this?

Hi @mmca28272, you’re not using the val parameter in the $.each() callback anywhere but setting the image source to the index; also the the imgs array actually already contains HTML (and possibly some empty) strings, not just the sources. Did you maybe mean to filter the images for PNGs? That might be done like so then:

data.filter(function (img) {
  return img.substring(img.lastIndexOf('.')) === '.png'
}).forEach(function (img, index) {
  $('<div class="carousel-item"><img class="d-block img-fluid" src="' + img + '"></div>').appendTo('.carousel-inner')
  $('<li data-target="#carousel" data-slide-to="' + index + '"></li>').appendTo('.carousel-indicators')
})
1 Like

Thanks a lot @m3g4p0p. It was a careless. Now it works properly.

1 Like

In fact, even by correcting each fuction, my original code will not work anyway since it returns <img src="images/image/image.png"></img> instead of images/image/image.png. Thanks again.

np :-)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.