Update a view of zf2 every 1s through jquery / ajax

2

I have a table as figure below, I need it to update every 1s, but I have no idea how to do it.

Iusedahtml5tag,butitupdateseverything,Ijustwanttoupdateonlythetable.MyView

<?php
$datenull = '01/01/0001 00:01';
$linha = 1;
?>
<meta HTTP-EQUIV="refresh" content="2">
<h1>Lista de Chamados em Abertos</h1>
<br/>
<div class="myTable table-responsive">
    <table class="table table-hover">
        <tr>
            <th></th>
            <th class="text-center">N. Chamado</th>
            <th class="text-center">Computador</th>
            <th class="text-center">Sala de Aula</th>
            <th class="text-center">Criado em</th>
        </tr>
        <?php foreach ($this->data as $entity) :?>
        <tr onclick="location.href ='<?php echo $this->url('Caos-admin-interna',
                array(
                    'controller' => 'calls',
                    'action' => 'examined',
                    'id' => $entity->getId()
                )
            );?>';" style="cursor: pointer">
            <td class="text-center"><strong><?php echo $linha;?></strong></td>
            <td class="text-center"><?php echo $entity->getId();?></td>
            <td class="text-center"><?php echo $entity->getComputer();?></td>
            <td class="text-center"><?php echo $entity->getClassroom();?></td>
            <td class="text-center"><?php echo $entity->getCreated();?></td>
        </tr>
        <?php
        $linha = $linha + 1;
        endforeach; ?>
    </table>
</div>
My Controller
<?php

namespace CaosAdmin\Controller;

use Zend\View\Model\ViewModel,
    Zend\Authentication\Storage\Session  as SessionStorage,
    Zend\Authentication\AuthenticationService;
use Zend\Paginator\Paginator,
    Zend\Paginator\Adapter\ArrayAdapter;


class CallsController extends CRUDController
{
    private $user;
    private $numberPerPage;
    public function __construct()
    {
        $this->entity = 'Caos\Entity\Call';
        $this->form = 'CaosAdmin\Form\Call';
        $this->service = 'Caos\Service\Call';
        $this->controller = 'calls';
        $this->route = 'Caos-admin';
        $auth = new AuthenticationService();
        $sessionStorage = new SessionStorage('CaosAdmin');
        $auth->setStorage($sessionStorage);
        $this->user = $sessionStorage->read();
        $this->numberPerPage = 20;
    }

    /**
     * @return ViewModel
     */
    public function indexAction()
    {
        $list = $this->getEm()->getRepository($this->entity)->findCallBySchool($this->user->getId());
        $viewModel = new ViewModel(array('data' => $list));
        return $viewModel;
    }
}

The return of my search comes in this format:

Array(
[0] => Caos\Entity\Call Object
    (
        [id:protected] => 27
        [examined:protected] => DateTime Object
            (
                [date] => 0001-01-01 00:00:00
                [timezone_type] => 3
                [timezone] => America/Sao_Paulo
            )

        [closed:protected] => DateTime Object
            (
                [date] => 0001-01-01 00:00:00
                [timezone_type] => 3
                [timezone] => America/Sao_Paulo
            )

        [modified:protected] => DateTime Object
            (
                [date] => 2017-01-20 16:21:39
                [timezone_type] => 3
                [timezone] => America/Sao_Paulo
            )

        [created:protected] => DateTime Object
            (
                [date] => 2017-01-20 16:21:39
                [timezone_type] => 3
                [timezone] => America/Sao_Paulo
            )

        [obs:protected] => 
        [computer:protected] => DoctrineORMModule\Proxy\__CG__\Caos\Entity\Computer Object
            (
                [__initializer__] => Closure Object
                    (
                        [static] => Array
                            (
                                [entityPersister] => Doctrine\ORM\Persisters\Entity\BasicEntityPersister Object
                                    (
                                        [class:protected] => Doctrine\ORM\Mapping\ClassMetadata Object
                                            (
                                                [name] => Caos\Entity\Computer
                                                [namespace] => Caos\Entity
                                                [rootEntityName] => Caos\Entity\Computer
                                                [customGeneratorDefinition] => 
                                                [customRepositoryClassName] => Caos\Entity\ComputerRepository
                                                [isMappedSuperclass] => 
                                                [isEmbeddedClass] => 
                                                [parentClasses] => Array
                                                    (
                                                    )

                                                [subClasses] => Array
                                                    (
                                                    )

                                                [embeddedClasses] => Array
                                                    (
                                                    )

                                                [namedQueries] => Array
                                                    (
                                                    )

                                                [namedNativeQueries] => Array
                                                    (
                                                    )

                                                [sqlResultSetMappings] => Array
                                                    (
                                                    )
  

leo_ap   the return of my search comes in this format:

Array(
[0] => Caos\Entity\Call Object
    (
        [id:protected] => 27
        [examined:protected] => DateTime Object
            (
                [date] => 0001-01-01 00:00:00
                [timezone_type] => 3
                [timezone] => America/Sao_Paulo
            )

        [closed:protected] => DateTime Object
            (
                [date] => 0001-01-01 00:00:00
                [timezone_type] => 3
                [timezone] => America/Sao_Paulo
            )

        [modified:protected] => DateTime Object
            (
                [date] => 2017-01-20 16:21:39
                [timezone_type] => 3
                [timezone] => America/Sao_Paulo
            )

        [created:protected] => DateTime Object
            (
                [date] => 2017-01-20 16:21:39
                [timezone_type] => 3
                [timezone] => America/Sao_Paulo
            )

        [obs:protected] => 
        [computer:protected] => DoctrineORMModule\Proxy\__CG__\Caos\Entity\Computer Object
            (
                [__initializer__] => Closure Object
                    (
                        [static] => Array
                            (
                                [entityPersister] => Doctrine\ORM\Persisters\Entity\BasicEntityPersister Object
                                    (
                                        [class:protected] => Doctrine\ORM\Mapping\ClassMetadata Object
                                            (
                                                [name] => Caos\Entity\Computer
                                                [namespace] => Caos\Entity
                                                [rootEntityName] => Caos\Entity\Computer
                                                [customGeneratorDefinition] => 
                                                [customRepositoryClassName] => Caos\Entity\ComputerRepository
                                                [isMappedSuperclass] => 
                                                [isEmbeddedClass] => 
                                                [parentClasses] => Array
                                                    (
                                                    )

                                                [subClasses] => Array
                                                    (
                                                    )

                                                [embeddedClasses] => Array
                                                    (
                                                    )

                                                [namedQueries] => Array
                                                    (
                                                    )

                                                [namedNativeQueries] => Array
                                                    (
                                                    )

                                                [sqlResultSetMappings] => Array
                                                    (
                                                    )

In my View I put this code to print the data:

$entity->getId()

In javascript what do I do? I have a method in my entity that transforms an array, how do I use it.

Thank you

    
asked by anonymous 17.01.2017 / 14:34

1 answer

0

You will need a Javascript function to populate your table dynamically. This function should dynamically request (ajax) your server to get the data to be inserted into the table. With this function ready, just create a setInterval that will make it run every second.

1st) Route and Controller for JSON Data Return

In your route file, define a route to get to a controller that should have a unique action for JSON data return. For example:

'chamados-get' => array(
    'type'    => 'literal',
    'options' => array(
        'route'    => '/chamado/get',
        'defaults' => array(
            'controller' => 'Application\Controller\ChamadoController',
            'action'     => 'get',
        ),
    ),
),

The above code should be inserted as an item in your route array, in the configuration of your module (file module.config.php ). Basically it points to the url /chamado/get , calling a controller Chamado and a get action. Named only as an example, you should replace the actual names you use in your application.

Now, the driver code must have this action get and it should do: a query to your database, get the data you want to display in the table and return it in JSON format:

<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class ChamadoController extends AbstractActionController
{
    public function getAction() {
        // Aqui voce deve fazer uma consulta ao seu banco de dados para retornar os dados em um array
        // Usei um array pronto como exemplo
        $data[0]['numchamado'] = '1123';
        $data[0]['computador'] = 'inf01';
        $data[0]['sala'] = 'S301';
        $data[0]['criadoem'] = '2017-01-18';

        $data[1]['numchamado'] = '1235';
        $data[1]['computador'] = 'inf03';
        $data[1]['sala'] = 'S302';
        $data[1]['criadoem'] = '2017-01-19';

        $data[2]['numchamado'] = '1443';
        $data[2]['computador'] = 'inf02';
        $data[2]['sala'] = 'S301';
        $data[2]['criadoem'] = '2017-01-20';

        $this->response->setContent(json_encode($data));
        return $this->response;
    }
}

Note that this action does not return a view. When we assign a value to $this->response->setContent and then return $this->response , we are creating a premature return type, which causes Zend not to look for view of action and just return content set to response . For more information on this, visit: link

With this, any request for seu-dominio/chamado/get will return the data of your bank in JSON format.

2nd) Javascript to Popular Table

Now what we need to do is create the javascript function that populates your table dynamically using the JSON data coming from the action we prepared in the previous step. Let's use jQuery to make our life easier:

<div class="myTable table-responsive">
    <table id="tbl-chamados" class="table table-hover">
        <thead>
        <tr>
            <th></th>
            <th class="text-center">N. Chamado</th>
            <th class="text-center">Computador</th>
            <th class="text-center">Sala de Aula</th>
            <th class="text-center">Criado em</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<script>
    function populateTable(){
        $.ajax({
            url: "<?php echo $this->url('chamados-get'); ?>",
            success: function(data){
                // Limpar tabela
                $('#tbl-chamados tbody').html("");

                // Popular a tabela com os dados vindos da requisição dinamica
                var dataJson = JSON.parse(data);
                var linha = 1;
                $.each(dataJson, function(){
                    $('<tr>').append(
                        $('<td>').text(linha++),
                        $('<td>').text(this['num_chamado']),
                        $('<td>').text(this['computador']),
                        $('<td>').text(this['sala']),
                        $('<td>').text(this['criadoem'])
                    ).appendTo('#tbl-chamados tbody');
                });
            }
        });
    }

    $(function(){
        setInterval(populateTable, 1000);
    });
</script>

The HTML of the table is then only with thead filled, we leave tbody empty because who will insert tr inside it will be Javascript. Javascript then comes just below, inside the tag script. It consists of a function called populateTable() and a call $(function(){..}) which is a shortcut to $(document).ready(...) .

The populateTable() function does the job of making a dynamic request for the url of the chamados-get route and bringing its return. This return is string JSON , which must be converted to objeto JSON and then routed. In this iteration it will create the tr of the table, with the columns and their values and then throw tr into tbody of the table.

The call of $(function(){..}) only sets a setInterval to call the function of popular the table every second (1000ms).

Basically that's it. Of course there may be many improvements in this process, but at the beginning you can start.

    
20.01.2017 / 14:42