List data with Ajax and PHP

Asked

Viewed 441 times

0

I have the following table

<?php foreach ($this->views->clients as $client): ?>
    <tr class="tr_<?= $client['id'];?>">
        <td><?= $client['id']; ?></td>
        <td><?= $client['name']; ?></td>
        <td><?= $client['email']; ?></td>
        <td><?= $client['nickname']; ?></td>
        <td><?= $client['hour_value']; ?></td>
        <td><?= $client['discount']; ?></td>
        <td><?= $client['date_pagment']; ?></td>
        <td><?= $client['cep']; ?></td>
        <td class="text-center"><a href="" class="glyphicon glyphicon-pencil"></a></td>
        <td class="text-center"><a href="" id="<?= $client['id']; ?>" class="getId glyphicon glyphicon-remove" data-toggle="modal" data-target="#myModal"></a></td>
    </tr>
<?php endforeach; ?>

on this very page has a modal which is a form that inserts the dados that will appear in this table, I would like to know what is the best way to load these dados dynamically with AJAX, would also like the new records to be displayed at the top of the table.

Code AJAX to insert dados:

// Register and list clients script
 $(function() {
     $('#AjaxRequestClient').submit(function(e) {
         e.preventDefault();
         var form = $(this).serialize(); // Pode ser usado serializeArray()
         var request = $.ajax({
             method: "POST",
             url: "/registerClient",
             data: form,
             dataType: "json",
             success: function() {

             }
         });

         request.done(function(e) {
             $('#msg').html(e.msg);
             $('.alert').removeClass('fade').addClass('alert-danger');

             if (e.status) {
                 $('#AjaxRequestClient').each(function() {
                     $('.alert').removeClass('alert-danger').addClass('alert-success');
                     this.reset();
                 });
             }
         });

         return false;
     });
 });
  • Which AJAX code you already have ready so far?

  • I edited and put the ajax code that inserts the data in the table, I wanted after inserting it plays the new record la to top..

  • I always use the first option, with the callback Success.

1 answer

1

I assume you are using jQuery. To put new content at the top of the table just use the function prepend (insert content at the beginning of an element). Something like this:

request.done(function(e){
        $('#msg').prepend(e.msg);
        //...
});

Depending on which element has the id #msg, there may be an unexpected result (if it is directly in the table tag and thead is included).

  • I don’t understand if he can use Success callback to use the request.done?

  • I think he is using it to check if there has been an error in the request (although it can be done using callback error, as in Success).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.