D.Wells D.Wells - 8 months ago 57
jQuery Question

dynamically inserting rows of json data into existing table

So I have a database results page displaying rows of data from one of my tables. I'm trying to implement a feature whereby if a user clicks on a certain row, additional data pertaining to that FK in another table will show up as rows of data beneath the clicked row, but above the next row of the original table. From what I've read there is no animation available for this- as long as it just appears in the right place I'll be happy. They can then be clicked again to hide.

I've already coded the on click function and have json data returning with the SQL queried data; I just don't know how to implement this feature with jquery as a javascript & jquery newcomer. Here is my attempt:

$(document).ready(function() {
$('.target_url').hover(function() {
$(this).css('cursor', 'pointer');

$( ".target_url" ).click(function() {
var url = $(this).html();
url: "post_results.php",
type: "POST",

data: { "blogger": url},
success: function( data) {
response = $.parseJSON(data);

$(function() {
$.each(response, function(i, item) {
var $tr = $(".target_url").append('<tr>' +
+ '</tr>'

error: function(xhr, status, error) {
console.log("not working");
dataType: 'text'

This code inserts the queried data into the ALL the fields of the first column of the original table. Obviously I need it added below just the originally clicked row, as a new seperate table row. I think this should be as simple as using the right selectors but I have only done some fairly basic form validation with jquery.

Would be really grateful for help!

Answer Source

Use this fiddle it may help.


var data =
       [{ id: 1, NAME: 'abc', POST_URL: 'qwert', POST_DATE: '123', },
        { id: 2, NAME: 'xyz', POST_URL: 'poiuy', POST_DATE: '456' },
        { id: 3, NAME: 'pqr', POST_URL: 'vbnmj', POST_DATE: '123' }];

        $('.target_url').click(function() {
                    var url = $(this).html();
                    $.each(data, function(i, item) {
                    var $tr=$('<tr></tr>');
                    $tr.append($('<td></td>',{text : item.NAME}));
                    $tr.append($('<td></td>',{text : item.POST_URL}));
                    $tr.append($('<td></td>',{text : item.POST_DATE}));