Patrick McDermott Patrick McDermott - 4 months ago 14
Ajax Question

JSON data not loading with jQuery

I want to load numerous products into a section of the page uaing data from a JSON file. I have got it to work using JavaScript, but I would prefer to use jQuery. There are no errors in the console, yet the data isn't loading. I am using Bootstrap. Relatively new to Ajax/JSON.

HTML

<div class="cat-group">
<div id="content"></div>
</div


CSS

.cat-group { overflow: hidden; }


jQuery

$(function(){

function loadProducts() {
$.getJSON('products.json')
.done( function(data){
products = data;
}).fail( function() {
$('#content').html('Sorry! We could not load our products at the moment. Try again later!');
});
}

loadProducts();

$(window).on('load', function(){

var newContent = ''; // Build up timetable by
for (var i = 0; i < products.length; i++) { // looping through events
newContent += '<div class="col-lg-3 col-md-4 col-xs-6">';
newContent += '<a class="thumbnail">';
newContent += '<h4>SKU: <span>' + products[i].product + '</span></h4>';
newContent += '<img class="img-responsive" src="' + products[i].img + '">';
newContent += '</a>';
newContent += '</div>';
}

$('#content').html(newContent);

});

})


JSON file

{
"products": [
{
"product": "product1",
"price": "10",
"sku": "1",
"img": "img/prod-1.jpg"
},
{
"product": "product2",
"price": "12",
"sku": "2",
"img": "img/prod-2.jpg"
},
{
"product": "product3",
"price": "13",
"sku": "3",
"img": "img/prod-3.jpg"
},
{
"product": "product3",
"price": "14",
"sku": "4",
"img": "img/prod-4.jpg"
}
]
}

Answer

I have made some changes in your code, Try this

$(function(){

            function loadProducts() {                    
                $.getJSON('products.json')              
                .done( function(data){                      
                    products = data.products;
                    renderProducts();
                }).fail( function() {                       
                    $('#content').html('Sorry! We could not load our products at the moment. Try again later!');
                });
            }

            loadProducts();                                      


        });


        function renderProducts() {

            var newContent = '';                               // Build up timetable by
            for (var i = 0; i < products.length; i++) {      // looping through events
                newContent += '<div class="col-lg-3 col-md-4 col-xs-6">';
                newContent += '<a class="thumbnail">';
                newContent += '<h4>SKU: <span>' + products[i].product + '</span></h4>';
                newContent += '<img class="img-responsive" src="' + products[i].img + '">';
                newContent += '</a>';
                newContent += '</div>';
            }

            $('#content').html(newContent);
        }