Saify
Saify

Reputation: 491

Display ajax response inside table

I want to display data from ajax response inside table.

Here is my table:

<table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table">
    <thead>
    <tr>
        <th class="centerText" data-field="item_id">ID</th>
        <th class="centerText" data-field="name">Name</th>
        <th class="centerText" data-field="price">Price</th>
        <th class="centerText" data-field="image">Image</th>
        <th class="centerText" data-field="edit">Edit</th>
    </tr>
    </thead>
    <tbody style="text-align:center;" id="menu_table_data"></tbody>
</table>

This is menu_table.php which gets data from database and returns response to ajax :

$output = '';
$search = mysqli_query($link,"SELECT menu.id, menu.name, menu.price, menu.image ORDER BY menu.id ASC;");

while($data = mysqli_fetch_array($search))
{
    $output .= '<td>'.$data['id'].'</td>
                <td>'.$data['name'].'</td>
                <td>'.$data['price'].'</td>
                <td><div id="div_image">
                <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div></td>
                <td><a class="btn btn-primary glyphicon glyphicon-edit" role="button"></a></td>
                ';
}
echo $output;

This is ajax function:

$(document).ready(function(){
    function fetch_data(){
        $.ajax({
            url: "menu_table.php",
            method: "POST",
            success: function(data){
                $('#menu_table_data').html(data);
            }
        });
    }
    fetch_data();
});

$('#menu_table_data').html(data); is showing data but not like table data. How can i show it inside table properly?

Upvotes: 1

Views: 3511

Answers (1)

Omi
Omi

Reputation: 4007

You have missed <tr></tr>.

try this:

$output = ''; 
$search = mysqli_query($link,"SELECT menu.id, menu.name, menu.price, menu.image ORDER BY menu.id ASC;"); 
while($data = mysqli_fetch_array($search)) { 
    $output .= '
    <tr>
      <td>'.$data['id'].'</td>
      <td>'.$data['name'].'</td>
      <td>'.$data['price'].'</td>
      <td>
        <div id="div_image">
          <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div>
      </td>
      <td>
        <a class="btn btn-primary glyphicon glyphicon-edit" role="button"></a>
      </td>
    </tr>
    '; 
}
echo $output;

Upvotes: 3

Related Questions