Datatable refresh/reload when table is built with php foreach loop

Datatable refresh/reload when table is built with php foreach loop

MatthewBarraudMatthewBarraud Posts: 5Questions: 3Answers: 0

Hi All, I wonder if any of you can help?

I have a datatable being built with a php foreach loop. The loop builds each row of the table in the DOM which I then initialise once the data is completed added.

On the first column I have an icon that the user can click to set the entry as published or not. I'm using Ajax to send a post request to update the database.

What I'm trying to do is reload the table again if successful. The documents suggest using table.ajax.reload(); but I get an Invalid JSON response. I think because I am not loading the data with JSON in the first place?

I can reload the whole page with location.reload but this is pretty laggy from a user's prospective if they are trying to publish many rows at once.

Does anyone know how to reload the table without ajax.reload? The foreach loop is supplied to the page by my db call.

Many thanks for any help!

This is my code so far...

    <tbody>
          <?php foreach ($data['voyageData'] as $voyage) : ?>
            <tr>
              <td class="text-center toggle" data-id="<?php echo $voyage->voyage_id; ?>" data-live="<?php echo ($voyage->voyage_live) ? '1' : '0'; ?>">
                <?php
                  if ($voyage->voyage_live) {
                    echo '<i class="far fa-toggle-on text-success fa-lg"></i>';
                  } else {
                    echo '<i class="far fa-toggle-off text-secondary fa-lg"></i>';
                  }
                ?>
              </td>
              <td>
                <?php echo ($voyage->voyage_featured == 1) ? ' ' : ' '; echo 'voyage_id.'">'.$voyage->voyage_name.''; ?>
              </td>
              <td data-sort="<?php echo date('Y-m-d', strtotime($voyage->voyage_startDate)); ?>">
                <?php echo date('jS M Y', strtotime($voyage->voyage_startDate)); ?>
              </td>
              <td data-sort="<?php echo date('Y-m-d', strtotime($voyage->voyage_endDate)); ?>">
                <?php echo date('jS M Y', strtotime($voyage->voyage_endDate)); ?>
              </td>
              <td>
                <?php echo $voyage->voyagetype_name; ?>
              </td>
              <td class="text-center">
                <a class="btn-sm btn-msp-lightblue text-white" href="">admin</a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>

And initialised with

<script>
      $(document).ready(function(){
        var table = $('#trips').DataTable({
           "order": [[ 2, "asc" ]],
        });

        $("#trips").on("click", ".toggle", function(event){
          console.log('click');
          var formData = {
            voyage_id: $(this).data("id"),
            voyage_live: $(this).data("live")
          };

          $.ajax({
            type: "POST",
            url: "<?php echo URLROOT.'/admin/publish-voyage'; ?>",
            data: formData,
            dataType: "json",
            encode: true,
          }).done(function (data) {
            if (!data.success) {
              console.log('fail');
              console.log(data.errors);
            } else {
              console.log('pass');
              //The update was successful, reload the table/refresh page to get new data.
              //location.reload(); //slow but works
              table.ajax.reload(); //gives error 
            }
          });

          event.preventDefault();
        });

      });
    </script>

Can anyone point me in the right direction?

Many thanks

Matt

Answers

  • colincolin Posts: 15,237Questions: 1Answers: 2,599

    Yep, ajax.reload() can only be called if you loaded the table Ajax to begin with (or if you have set a URL later). If your publishing script is updating the data in the DOM, you can just call rows().invalidate(), than draw(), and that'll refresh the table with the DOM data.

    Colin

  • MatthewBarraudMatthewBarraud Posts: 5Questions: 3Answers: 0

    Hi @colin

    Thanks so much for your reply.

    I think I'm stuck on the refreshing the DOM part, I have

    $("#trips").load(location.href+" #trips>*","");
    table.rows().invalidate().draw(false);
    

    Which is updating the records, however I seem to loose part of the datatable functionality. When I use the above the table reloads but shows all records (18) instead of pagination (but still shows page 1/2 etc) and the sorting is broken.

    I'm missing the vital piece of understanding I think.

  • colincolin Posts: 15,237Questions: 1Answers: 2,599

    It seems to be behaving here: http://live.datatables.net/fojidihi/1/edit

    Could you look at that, please, and see if it helps. If it's still not working for you, please can you update my example, or link to your page, so that we can see the problem.

    Cheers,

    Colin

This discussion has been closed.