Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying JSON array through ajax (jquery)

I'm pretty new to Ajax and JSON and tried to get this to work but can't seem to get the hang of it.

How do I call the json in ajax and display all the info inside the json file?

here's my json file

{
  posts: [{
    "image": "images/bbtv.jpg",
    "alter": "BioBusiness.TV",
    "desc": "BioBusiness.TV",
    "website": "http://andybudd.com/"
  }, {
    "image": "images/grow.jpg",
    "alter": "Grow Staffing",
    "desc": "Grow Staffing",
    "website": "http://growstaffing.com/"
  }]
}

and the ajax function im using

$.ajax({
  type: "GET",
  url: "category/all.js",
  dataType: "json",
  cache: false,
  contentType: "application/json",
  success: function(data) {

    $.each(data.posts, function(i, post) {
      $('#folio').html('<ul><li><div class="boxgrid captionfull"><img src="' + post.image + '" alt="' + post.alter + '" /><div class="cover boxcaption"><p>' + post.desc + '</p><a href="' + post.website + '" target="_blank">More Work</a></div></div></li></ul>');

    });
    initBinding();
  },
  error: function(xhr, status, error) {
    alert(xhr.status);
  }
});

For some reason, it's only displaying the last item....

Any help in the right direction would be great.

Thanks!

like image 576
eek meek Avatar asked Jun 11 '26 18:06

eek meek


2 Answers

Try something like this:

$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
   $('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' + post.image + '" alt="' + post.alter + '" /><div class="cover boxcaption"><p>' + post.desc + '</p><a href="' + post.website + '" target="_blank">More Work</a></div></div></li>');
});
like image 74
kgiannakakis Avatar answered Jun 14 '26 08:06

kgiannakakis


you are overwriting the html in #folio each loop, you need to concatinate onto it

try adding the UL first then append to the UL a LI for each loop .append() instead

like image 40
Pharabus Avatar answered Jun 14 '26 07:06

Pharabus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!