Reputation: 35
I am trying to Display Json data which contain Array of image and para in bootstrap card using for loop it displays cards but display image only in one card but there are five cards.
Json file contents:
[{"image" : "abc.png" , "para" : "Hi..iam rohit.and this 1st card"},{"image" : "sqr.png", "para" : "Hi..iam rakesh.and this 2st card"},{...},{....}...]
Card is being displayed within:
<div class="row" id="printcard">
</div>
Associated Ajax.js:
var vimg;
var html ='<div class="col-md-12">';
html +='<div class="card">';
html +='<div class="row">';
html +='<div class="col-md-4" id="userimg"> </div>';
html +='<div class="col-md-8 px-3">';
html +='<div class="card-block px-3">';
html +='<h4 class="card-title">sometitle</h4>';
html +='</div>';
html +='</div>';
html +='</div>';
html +='</div>';
html +='</div>';
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'http://localhost:8080/demo/Json',
dataType: 'json',
success: function (data) { /* Here data length is 5*/
for(var i=0;i<data.length;i++){
$('#printcard').append(html);
uimg=data[i].image;
var $img = $("<img/>");
$img.width('340px');
$img.height('220px');
$img.attr("src", "data:image/png;base64," + uimg);
$("#userimg").append($img);
}
}
});
});
When I run this example, it displays 5 cards, but only the first card has an image. How do I fix this and how do I print Json data/Para in each card.
Upvotes: 2
Views: 6935
Reputation: 650
I guess the problem is in the iteration, you should use $.each, but if you want to stick to the for, do this:
uimg=data.image[i];
Upvotes: 1
Reputation: 13801
You have 2 problems
id="userimg"
id can be only one for one element$("#userimg").append($img);
this will select the first one only So change this two things
html +='<div class="col-md-4" id="userimg"> </div>'
to
html +='<div class="col-md-4 userimg" > </div>'
and
$("#userimg").append($img);
to
$(".userimg:eq("+i+")").append($img);
var vimg;
var data=[{"image" : "abc.png" , "para" : "Hi..iam rohit.and this 1st card"},{"image" : "sqr.png", "para" : "Hi..iam rakesh.and this 2st card"}]
var html = '<div class="col-md-12">';
html += '<div class="card">';
html += '<div class="row">';
html += '<div class="col-md-4 userimg"> </div>';
html += '<div class="col-md-8 px-3">';
html += '<div class="card-block px-3">';
html += '<h4 class="card-title">sometitle</h4>';
html += '</div>';
html += '</div>';
html += '</div>';
html += '</div>';
html += '</div>';
for (var i = 0; i < data.length; i++) {
$('#printcard').append(html);
uimg = data[i].image;
var $img = $("<img/>");
$img.width('340px');
$img.height('220px');
$img.attr("src", "data:image/png;base64," + uimg);
$(".userimg:eq("+i+")").append($img);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row" id="printcard">
</div>
Upvotes: 1