mvasco mvasco - 8 months ago 28
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").on("slide", function(slideEvt) {

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

$.post('search.php', { keywords: searchKeyword }, function(data) {
$('#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>');

}, "json");

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?


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);
// 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.