0
votes

Jquery Code

<script type="text/javascript">
$(document).ready(function()
{
$.getJSON("http://localhost/index.php/upload/history",function(data)
{
$.each(data.images, function(i,data)
{
$('#recent').html( '<img src="/t/'  +data.imagename + '">' );
});
}
);
return false;
});
</script>

sample json data

{
    "images": [
        {
            "imagename": "p5Tsa.jpg"
        },
        {
            "imagename": "Z8hjA.jpg"
        },
        {
            "imagename": "0Fnm0.jpg"
        },
        {
            "imagename": "D5Tfa.jpg"
        },
        {
            "imagename": "VDnvu.jpg"
        },
        {
            "imagename": "9spgp.jpg"
        },
        {
            "imagename": "Hg7va.jpg"
        }
    ]
}

This shows only the first image .. but when I use append() , then it shows all the images thats in the json response.. the reason I want to avoid append is that I want to refresh the div usng setInterval().

How to show all the images that I get in the json response using .html() ?

thanks :)

2

2 Answers

2
votes

Use append, but clear the html on each fetch.

<script type="text/javascript">
$(document).ready(function()
{
$.getJSON("http://localhost/index.php/upload/history",function(data)
{
$('#recent').html("");
$.each(data.images, function(i,data)
{
$('#recent').append( '<img src="/t/'  +data.imagename + '">' );
});
}
);
return false;
});
</script>
2
votes

When you call html() you are setting the whole content of the element. There are several ways to solve this. I would do

$.getJSON("http://localhost/index.php/upload/history",function(data) {
    var images = $.map(data.images, function(data) {
        return '<img src="/t/'  +data.imagename + '">';
    }).get();
    $('#recent').html(images.join(''));
});

to only insert into the document once.

You could easily do the same with append, you just have to clear the content before.