BarclayVision BarclayVision -4 years ago 91
jQuery Question

Assign ajax data val to table header

In my ajax call I want to assign each

key
as a
<td>
to a single row in the
$('#shelf .table thead tr')
. This is my attempt that is not working.

AJAX:

function ajax_call($aff){
$.ajax({
url: 'fill_crosstab.php',
data: {action:$aff},
dataType: 'json',
success: function(data){
$('#shelf .table tbody').empty();

$('#shelf .table thead tr').empty();
for ( var i = 0; i < key.length; i++ ) {
out += "<td>" + key[i] + "</td>";
}
$('#shelf .table thead tr').append(out + "</tr>");

if ($aff == "database") {
$.each(data, function(key, val) {
$('.dropdown-menu').append("<a class='dropdown-item' href='#'>" + val.Affiliation + "</a>");
});
// Bind the event now, after the html element has bend created.
$(".dropdown-menu a").on("click", function () {
var selText = $(this).text();
$('.shelf-header').empty();
$('.shelf-header').append(selText);
ajax_call(selText);
});
} else {
$.each(data, function(key, val) {
$('#shelf .table tbody').append("<tr><td>" + val.LAST + "</td><td>" + val.FIRST + "</td><td>" + val.MDC + "</td><td>" + val.RADIO + "</td><td>" + val.eMEDS + "</td><td>" + val.FireApp + "</td><td>" + val.P1 + "</td></tr>");
});
}
}
});
};


JSON DATA:

[{"LAST":"JONE","FIRST":"MARY","MDC":"07\/23\/2003","RADIO":"08\/22\/2002","eMEDS":"02\/09\/2015","FireApp":"09\/11\/2012","P1":" "}]

Answer Source

If you require the for loop to create the headers of the table, extracting the keys from the data, you will need to use the first row.

You should also retain the keys of that row to use to ensure that the other rows line up in the same columns. I note you use "." to get those as properties in the else clause at the bottom of that snippet.

Start by getting those keys - put this near the top of the success handler:

var keys = Object.keys(data[0]);

Now you can loop over this to create your first row (put this in the thead section):

for ( var i = 0; i < keys.length; i++ ) {
    out += "<td>" + keys[i] + "</td>"; 
}

In that else section, the tbody, you can do this to make sure it matches up. This references that keys variable above, in the same order, and uses the key there to look up the value in the item:

$.each(data, function(_k, val) {
    var out = "<tr>";
    for( var i =0; i< keys.length; i++) {
       out += "<td>" + val[keys[i]] + "</td>";
    }
    out += "</tr>";
    $('#shelf .table tbody').append(out);
});

In this snippet here - the "_k" is the row number, I've prefixed it with an underscore to make it clear to a reader that we're not interested in it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download