mvasco mvasco - 7 months ago 24
HTML Question

HTML table not showing content in columns

A user can search for people included in a database introducing the search terms in an input text.
I am using following Ajax script to show the database objects received from JSON:

<script type="text/javascript">
$(document).ready(function() {

// With JQuery
$("#ex6").slider();
$("#ex6").on("slide", function(slideEvt) {
$("#ex6SliderVal").text(slideEvt.value);
});

$('#keyword').on('input keyup change', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length < 3) {
$('ul#content').empty()
}
if (searchKeyword.length >= 1) {

$.post('search.php', { keywords: searchKeyword }, function(data) {
$('#content').empty()
$('#content').append('<table class="table table-hover"><thead><tr><th>First Name</th><th>Last Name</th><th>Username</th></tr></thead><tbody>')

if (data == ""){
$('#content').append('No hay resultados para su búsqueda')
}

$.each(data, function() {


$('#content').append('<tr><td>'+this.nombre_doctor +'</td><td>'+ this.apellido1_doctor + '</td><td>'+ this.apellido2_doctor+'</td></tr>');


});
$('#content').append('</tbody></table>')
}, "json");
}
});
});
</script>


And this is the output when a user introduces a search term:

enter image description here

As you may see in the picture, the objects are not shown on the expected column.

What is wrong in the script?

Answer

When you call append with a string, jQuery constructs an object and appends that. In other words, append('<foo>') is really append($('<foo'>). The assumption in this code that append appends raw HTML is incorrect.

You want something like

var $table = $('<table class="table table-hover"><thead><tr><th>First Name</th><th>Last Name</th><th>Username</th></tr></thead></table>').appendTo('#content');
var $tbody = $('<tbody></tbody>').appendTo($table);

$.each(data, function() {
    var $tr = $('<tr>').appendTo($tbody);
    $('<td>').text(this.nombre_doctor).appendTo($tr);
    $('<td>').text(this.apellido1_doctor).appendTo($tr);
    $('<td>').text(this.apellido2_doctor).appendTo($tr);
});
// Nothing with </tbody></table> , those elements already exist

Note that your current code includes a significant vulnerability as it allows everybody who controls your data to inject arbitrary HTML and JavaScript into your website. The use of text avoids this.