Friday, February 17, 2012

jQuery JSON response into table column


The excerpt below is part of a .ajax() function I'm using to pull data from a database. The database is queried using PHP and the output sent back in JSON format. Only 1 row of data is returned by the function.




success: function(data) {
for(var key in data) {
$("#formTable tr").find("td:eq(1)").text(data[key]);
}
}



I have an HTML table on the page which is split into two columns. The left column has field labels, the right column is empty.



I would like to cycle through my JSON reply for each key/value pair. I would like to insert the value into the right hand column table cell. The code should cycle through until all key/value pairs have been output onto the next table row, into the next right hand table cell.



The code above selects the second column table cell but inserts the last JSON value into all cells instead of each value going into its' own table cell in the column.



I think if I can get the selector right this will work, I'm just not sure what that should be..



Thanks.

1 comment:

  1. You are basically selecting all the rows of the table and second td from the whole set of table rows in each iteration so it isn't working as expected.

    Assuming that the json response has one to one mapping of keys and the field labels in the table you can try this.

    success: function(data) {
    var fieldCount = 0,
    $tableRows = $("#formTable tr");
    for(var key in data) {
    $tableRows.eq(fieldCount++).find("td:eq(1)").text(data[key]);
    }
    }

    ReplyDelete