Youness Benbiga Youness Benbiga - 2 months ago 20
Ajax Question

Ajax not working with owl-carousel

I m having a probleme with implementing ajax in my page which countain owl-carousel her is the code :

Controller:

public int Getmembers()
{

return db.Teams.Count();

}
}


The View :

<script>
$(document).ready(function () {
var json = null;
$.ajax({
url: '@Url.Action("Getmembers", "Home")',
type: "GET",
dataType: "int",
success: function (data) {
json = data;

},
error: function () {
alert("Erreur de récupération des membres ou il n'existe aucun memnbre");
}

})
alert(json);
var owl = $("#owl-demo");

owl.owlCarousel({
items: json, //10 items above 1000px browser width
itemsDesktop: [1000, 5], //5 items between 1000px and 901px
itemsDesktopSmall: [900, 3], // betweem 900px and 601px
itemsTablet: [600, 2], //2 items between 600 and 0
itemsMobile: false, // itemsMobile disabled - inherit from itemsTablet option
pagination: false

});


});
</script>


I tried debugging and i discovered that in the $.ajax the value of json is passed (an int 13) but when i use alert i get null , i searched in the documentation got this http://www.jq22.com/demo/OwlCarousel2/demos/ajax.html but still having no clue.

Answer

Your ajax call is async which means it will execute the success method after your owl carousel initialization.

Put the init method of your carousel into the success method:

    $(document).ready(function () {
    var json = null;
    $.ajax({
        url: '@Url.Action("Getmembers", "Home")',
        type: "GET",
        dataType: "int",
        success: function (data) {
            var owl = $("#owl-demo");

            owl.owlCarousel({
                items: data, //10 items above 1000px browser width
                itemsDesktop: [1000, 5], //5 items between 1000px and 901px
                itemsDesktopSmall: [900, 3], // betweem 900px and 601px
                itemsTablet: [600, 2], //2 items between 600 and 0
                itemsMobile: false, // itemsMobile disabled - inherit from itemsTablet option
                pagination: false

            });

        },
        error: function () {
            alert("Erreur de récupération des membres ou il n'existe aucun memnbre");
        }

    });
});