Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

$.ajax({
  url: '<?php echo base_url('ads/select_post'); ?>',
   data: {},
   dataType: "json",
   cache: false,
   success: function (data) {
     $.each(data, function (i, val) { 
       console.log(val.name);
       $("#name").html(val.name);
       $("#price").html(val.price);
       $("#addr").html(val.addr);
       $("#des").html(val.des);
       $("#viewed").html(val.viewed);
       $("#status").html(val.status);
    });
 }
});

Console output:

[{"name":"dfasdfas","price":"0","addr":"dfasdfas","des":"sadfdfasdfasdf","viewed":"0","img":"","status"
:"1"},{"name":"Heng","price":"0","addr":" dflkas;df","des":"asdfasdf"
,"viewed":"0","img":"","status":"1"},{"name":"asdDasdA","price":"0","addr":"asdADasd","des":"ASDasdASD"
,"viewed":"0","img":"","status":"1"},{"name":"asdfas","price":"0","addr":"fasdfas","des":"dfasdf","viewed"
:"0","img":"","status":"1"},{"name":"asdf","price":"0","addr":"asdfasdfas","des":"asdfasdfasdf","viewed"
:"0","img":"","status":"1"}]

HTML of the table i am sending data to,

<tbody id="items">
 <tr>
  <td>1</td>
  <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> 
 </tr>

Please advise.

share|improve this question
3  
I think you have to create table rows dynamically –  syms 9 hours ago
    
Because you use id selector (id="name", id="price"...) and your code does append any new table row, so that no new row in the table will be created. Don't use id selector in your template, you need to travel through your data and append a new row. –  truongnguyen1912 9 hours ago

10 Answers 10

up vote 6 down vote accepted

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"
,"viewed":"0","img":"","status":"1"},{"name":"asdDasdA","price":"0","addr":"asdADasd","des":"ASDasdASD"
,"viewed":"0","img":"","status":"1"},{"name":"asdfas","price":"0","addr":"fasdfas","des":"dfasdf","viewed"
:"0","img":"","status":"1"},{"name":"asdf","price":"0","addr":"asdfasdfas","des":"asdfasdfasdf","viewed"
:"0","img":"","status":"1"}];

//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);
  currRow.find('.name').html(val.name);
  currRow.find('.price').html(val.price);
  currRow.find('.addr').html(val.addr);
  currRow.find('.des').html(val.des);
  currRow.find('.viewed').html(val.viewed);
  currRow.find('.status').html(val.status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody id="items">
    <tr id="tr0">
      <td>Id</td>
      <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>
    </tr>
  </tbody>
</table>

share|improve this answer
1  
@Machkan This is the best one I'm thanks you very much. –  Cambodia channel 8 hours ago
    
@Cambodiachannel You're welcome. I updated the code slightly to use a variable instead of continually calling the row id. Happy coding! –  Mackan 8 hours ago
1  
@Mackan That is a good one. If Cambodiachannel wants the data from the json only needs to be in the table, he can remove all the rows before appending the first clone –  Marikkani Chelladurai 8 hours ago
1  
Agreed @Mackan. Indeed this is the good one.. :) –  Guruprasad Rao 8 hours ago

You probably need some code like this, This is rough idea you can let me know if you don't get it

this.tableElement = jQuery('<table/>', {
}).appendTo(gridWrapElement);

var tableBody = jQuery('<tbody/>', {
    'class': 'eg-table-body'
});

this.tableBodyRow = jQuery('<tr/>', {
});

var scope = this;
var columns = [{
        name:"Name",
        dataIndex:"name",
        width: "33%"
    },{
        name:"Price",
        dataIndex:"price",
        width: "33%"
    },{
        name:"Address",
        dataIndex:"addr",
        width: "34%"
    }];
$.each(this.columns, function(index, column) {
    var tableBody = jQuery('<td/>', {
        width: column.width,
        columnDataIndex: column.dataIndex,
        columnIndex: index
    });

    jQuery('<div/>', {
        html: "<a>" + column.name + "</a>",
        class: "eg-table-Body-div"
    }).appendTo(tableBody);

    tableBody.appendTo(scope.tableBodyRow);
    scope.tableBodyItems.push(tableBody);
});

jQuery(this.tableBodyRow).appendTo(tableBody);
jQuery(tableBody).appendTo(this.tableElement);
share|improve this answer
    
I don't know how to send to html –  Cambodia channel 8 hours ago

You can try this, I test it locally and it works:

$.ajax({
    url: '<?php echo base_url('ads/select_post'); ?>',
    data: {},
    dataType: "json",
        cache: false,
        success: function (data) {
        $.each(data, function (i, val) {
            var tr = "<tr>" +
                "<td>"+ (i + 1) + "</td>" +
                "<td>"+ val.name + "</td>" +
                "<td>"+ val.price + "</td>" +
                "<td>"+ val.addr + "</td>" +
                "<td>"+ val.des + "</td>" +
                "<td>"+ val.viewed + "</td>" +
                "<td>"+ val.status + "</td>" +
                "</tr>";
            $(tr).appendTo("tbody");
        });
    }
});

And your html table:

<table>
    <tbody id="items">

    </tbody>
</table>
share|improve this answer
    
You used tr to appenTo but if I have two or three table How should I used ID instead of this –  Cambodia channel 8 hours ago

It is better if you can rows dynamically. Then append generated html into tbody table like example below :

HTML

<table>
<tbody id="items">
    <tr>
        <td>No.</td>
        <td>name</td>
        <td>price</td>
        <td>addr</td>
        <td>des</td>
        <td>viewed</td>
        <td>status</td>
    </tr>
</tbody>

JS

var data = [{
"name": "dfasdfas",
    "price": "0",
    "addr": "dfasdfas",
    "des": "sadfdfasdfasdf",
    "viewed": "0",
    "img": "",
    "status": "1"
}, {
"name": "asdDasdA",
    "price": "0",
    "addr": "asdADasd",
    "des": "ASDasdASD",
    "viewed": "0",
    "img": "",
    "status": "1"
}];

/************ put this inside ajax success block*/
var output;
$.each(data, function (i, val) {
output += '<tr><td>' + i + '</td>' +
    '<td><a><div id="name">' + val.name + '</div> </a></td>' +
    '<td><a><div id="price">' + val.price + '</div> </a></td>' +
    '<td><a><div id"addr">'+ val.addr +'</div></a></td>' +
    '<td><div id="des">' + val.des + '</div> </td>' +
    '<td><a><div id="viewed">' + val.viewed + '</div></a></td>' +
    '<td><a><div id="status">'+
val.status+'</div></a></td></tr>';
});

$('#items').append(output);
/************ end */

DEMO

share|improve this answer

You need something like this:

DEMO HERE

HTML Structure

<table>
    <thead>
        <th>Sl No.</th>
        <th>Address</th>
        <th>Description</th>
        <th>Image</th>
        <th>Name</th>
        <th>Price</th>
        <th>Status</th>
        <th>Viewed</th>
    </thead>
    <tbody id="items">
    </tbody>
</table>

JS

    $.each(data, function (i, val) { 
           $("tbody#items").append("<tr><td>"+(i+1)+"</td><td><a><div>"+val.addr+"</div></a></td>"
                +"<td><a><div>"+val.des+"</div></a></td>"
                +"<td><a><div>"+val.img+"</div></a></td>"
                +"<td><a><div>"+val.name+"</div></a></td>"
                +"<td><a><div>"+val.price+"</div></a></td>"
                +"<td><a><div>"+val.status+"</div></a></td>"
                +"<td><a><div>"+val.viewed+"</div></a></td></tr>");
    });
share|improve this answer

You need to create table rows() in the ajax success.
And you should not use same ids in the td tags.

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

        html +="<tr>";
        html += "<td>" + val.name + "</td>" ;
        html += "<td>" + val.price + "</td>" ;
        html += "<td>" + val.addr + "</td>" ;
        html += "<td>" + val.des + "</td>" ;
        html += "<td>" + val.viewed + "</td>" ;
        html += "<td>" + val.status + "</td>" ;
        html +="</tr>";
    });
    $("$items").html(html);
  }
});

Your html:

<table>
    <tbody id="items">

    </tbody>
</table>
share|improve this answer
    
You can use appendTo() like this. $(html).appendTo("#items"); –  baris usanmaz 8 hours ago
var body = '';
$.each(val,function(i,j){
  body = body + '<tr><td>'+i+1+'</td>';
  body = body + '<td>'+j.name+'</td>';
  body = body + '<td>'+j.price+'</td>';
  body = body + '<td>'+j.addr+'</td>';
  body = body + '<td>'+j.des+'</td>';
  body = body + '<td>'+j.viewed+'</td>';
  body = body + '<td>'+j.status+'</td></tr>';
});
$('#items').html(body);

This will give you the table with values

share|improve this answer

Try this. Its shows all data in table. http://jsfiddle.net/Navneethk/zcpp51tc/2/

share|improve this answer
    
This can go in comments. There is plenty of land available there.. :) –  Rohit416 8 hours ago
var html = '<tr>';
 for(var i = 0 ;i < data.length;i++){ 
  var val = data[i];
  html += '<td>'+i+'</td>'+
            '<td><a><div id="name'+id+'">'+ val.name +'</div> </a></td>'+ 
            '<td><a><div id="price'+id+'">'+ val.price +'</div> </a></td>'+ 
            '<td><a><div id"addr'+id+'">+ val.addr +</div></a></td>'+ 
            '<td><div id="des'+id+'">' +val.des+ '</div> </td>'+ 
            '<td><a><div id="viewed'+id+'">'+ val.viewed +'</div></a></td>'+ 
            '<td><a><div id="status'+id+'">' val.status '</div></a></td>';
}

 $("#items").html(html);
share|improve this answer
2  
There should not be id of the div in for loop, as it will not make sense at all, cause you can assign single id to single item only. –  Parag Bhayani 9 hours ago
    
@ParagBhayani I am assigning single id to single item. –  Kulwant Singh 9 hours ago
    
If there are 15 items in data array then it will create 15 divs with '<div id="name">' and, so 15 divs with single id is not what it should be... I hope you got this... –  Parag Bhayani 9 hours ago
    
@ParagBhayani yes 15 items in data array will create 15 different rows and each rows has id associated with it. –  Kulwant Singh 8 hours ago
    
@ParagBhayani please refer my second line in for loop. –  Kulwant Singh 8 hours ago

You were assigning all 5 data row to the same template so that you only see the last data set returned. You should create those 5 row dynamically by using createElement or jQuery.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.