user3920645
user3920645

Reputation: 45

Update HTML from AJAX

My table is appended to instead of updated. What would be the appropriate way to update the html. I tried to use the answer from a similar stackoverflow question but it didn't work.

Here's my webpage, which uses Bootstrap, and the relevant ajax:

<div class="bs-component">
  <table class="table table-striped table-hover ">
      <thead>
      <tr>
          <th style="font-size: 25px">Week <span id="week" style="font-size: 28px">1</span></th>
          <th>12 am - 8 am</th>
          <th>8 am - 12 pm</th>
          <th>12 pm - 4 pm</th>
          <th>4 pm - 8 pm</th>
          <th>8 pm - 12 am</th>

      </tr>
      </thead>
      <tbody>
          <script>
          function loadWeek (x) {
            $.post("weekly.php", {p: x}, function (res) {
               //$("tbody").append(res);
               $('#bs-component table > tbody:last').find('tr:first').before(res);
            });
          }
          $(function () {
            loadWeek (1);
          });
          </script>
      </tbody>
  </table>

Here's the html echoed by the php called by ajax

for ($i = 0; $i < 7; $i++) {
    echo "<tr><td>$weekDays[$i]</td>";
    for ($j = 0; $j < 5; $j++) {
        echo "<td><p>".$usersNames[$i][$j]."</p></td>";
    }
    echo"</tr>";
}

Upvotes: 0

Views: 69

Answers (1)

Bill Hannah
Bill Hannah

Reputation: 36

I see a few small issues with your jQuery code. First, you want to move the <script> tag out of the table. It can be anywhere in the page, and typically goes at the bottom of the page (just before the closing body tag </body>). The reason you want to do this is that when the Ajax response returns, you want to replace the contents of the <tbody> which will overwrite your <script> tag.

Next, what you want to do with the response is replace the contents of the <tbody> (rather than append). I would rewrite your loadWeek function as follows:

function loadWeek(x) {
  $.post('weekly.php', {p: x}, function(res) {
    $('#bs-component tbody').html(res);
  });
}

You can find the documentation for the .html() function at https://api.jquery.com/html/

Notice the selector is slightly different - because you only have 1 <table> inside your <div>, and that table only has 1 <tbody> inside that table, you don't have to specify the last <tbody> that is a direct descendant of a <table> (which is what the selector you have means).

Upvotes: 1

Related Questions