Vương Vũ Nguyễn
Vương Vũ Nguyễn

Reputation: 106

Ajax refresh table after database updated in cakephp?

How can i refresh content of table like this after call a ajax for submit database in controller. I use cakephp.

<table id="example" class="table">
<thead>
    <tr class="headings">
        <th>ID &nbsp;&nbsp;&nbsp;</th>
        <th>first name </th>
        <th>last name </th>
        <th>E-mail </th>
        <th>birthday </th>
    </tr>
</thead>

<tbody>
    <?php // empty for now ?>
</tbody>

My ajax:

(function($) {
   $.fn.ApplyTask = function() {
       var task_id = $(this).data('task');
       var user_id = $(this).data('user');

       $.ajax({
           url: 'applyTask',
           cache: false,
           type: 'POST',
           data: {
               task_id: task_id,
               user_id: user_id
           },
           success: function(data) {

               }
           });
       };
   })($);

And function applyTask only update value for database.

public function applyTask() {
    if ($this->request->is('ajax') && !empty($this->request->data)) {
        $task_id = $this->request->data['task_id'];
        $user_id = $this->request->data['user_id'];

        if (!$this->TasksUser->findByTaskIdAndUserId($task_id, $user_id)) {
            throw new NotFoundException(__('Invalid tasks_users.'));
        }

        $this->TasksUser->updateAll(array('is_apply' => TRUE), array('task_id' => $task_id, 'user_id' => $user_id));
    } else {
        throw new MethodNotAllowedException('This method is now allowed.');
    }
}

Upvotes: 0

Views: 568

Answers (1)

Alimon Karim
Alimon Karim

Reputation: 4469

In your applyTask.ctp file fetch data only in tr

example :

<?php foreach ($data as $data): ?>
       <tr>
              <td><?= h($data->id) ?></td>
              <td><?= $data->username ?></td>
        </tr>
<?php endforeach; ?>

Then in your tbody add an id or class, example

<tbody id="fetch-data">
    <?php // empty for now ?>
</tbody>

Now in callback just add data by below code

success: function(data) {
    $('#fetch-data').html(data);
}

Note : don't forget to use $this->viewBuilder()->layout(false); in your applyTask method.

Upvotes: 1

Related Questions