Javascript – How to send data from Json using Ajax in jquery for html element


I am trying to show data from 5 rows of Database (MySQL) to rows of table using on success of jQuery AJAX call. The data is in JSON format.

Issue: I am not able to figure out to get all of those rows. I can get only one row but console showed me all the rows in JSON format.

  url: '<?php echo base_url('ads/select_post'); ?>',
   data: {},
   dataType: "json",
   cache: false,
   success: function (data) {
     $.each(data, function (i, val) { 

Console output:

:"1"},{"name":"Heng","price":"0","addr":" dflkas;df","des":"asdfasdf"

HTML of the table i am sending data to,

<tbody id="items">
  <td><a><div id="name"></div> </a></td> 
  <td><a><div id="price"></div> </a></td> 
  <td><a><div id"addr"></div></a></td> 
  <td><div id="des"></div> </td> 
  <td><a><div id="viewed"></div></a></td> 
  <td><a><div id="status"></div></a></td> 

Please advise.

Best Solution

Lots of good answers, but since I've created an example I'll post that too. If nothing else it might give you, or someone else, an alternative solution. I'm using classes instead of Id's, and keep your original structure.

Since this was accepted as answer I should also mention why your code failed:
Your each loop is continually overwriting the contents of your table row data, instead of creating new rows. Another thing that needed fixing is that you had given the columns Id's, and those cannot stay (as they were) if you want to repeat the rows, since Id's within a page must be unique.

There are many methods to create new elements. I chose clone() as I figure you would always have a row for header that could easily be used to clone/copy. Also I added a unique Id attribute to each tr. These are not really used in the current implementation below, but it might be good to have as reference later in your project.

var data = [{"name":"dfasdfas","price":"0","addr":"dfasdfas","des":"sadfdfasdfasdf","viewed":"0","img":"","status"
:"1"},{"name":"Heng","price":"0","addr":" dflkas;df","des":"asdfasfasdfasdfasdfasdfasfasdfasdfasdfas"

//place within the Ajax success
$.each(data, function(i, val) {
  var currRow = $("#tr0").clone().appendTo($('#items')).attr('id','tr' + (i + 1));
  currRow.find('td:eq(0)').html(i + 1);
<script src=""></script>
  <tbody id="items">
    <tr id="tr0">
      <td><a><div class="name">Name</div></a></td>
      <td><a><div class="price">Price</div></a></td>
      <td><a><div class="addr">Addr</div></a></td>
      <td><div class="des">Des</div></td>
      <td><a><div class="viewed">Viewed</div></a></td>
      <td><a><div class="status">Status</div></a></td>