How to update a helper function with ajax

Asked

Viewed 55 times

0

Hello, I need help that gave a knot in the head, I am working with codeigniter, I have created three functions in my helper consulting the database, and I display a result in Divs with the amounts of records, I call these three helper functions in all controls, but now I need to use ajax to update these functions in real time, that’s why I stopped, because I don’t know how to call these helper functions to be updated in real time. If you can help me by giving me a light, thank you. My code is like this:

my helper called: funcao_helper:

 function np()
       {
            // Obter uma referência ao objeto do controlador
            $CI = get_instance();
            //carrega o banco de dados
            $CI->load->model('dashboard_model');

            $np = $CI->dashboard_model->contarNotasPendentes();

           return $np;//retorna a quantidade de registros
       }

       function vf()
       {
            // Obter uma referência ao objeto do controlador
            $CI = get_instance();
            //carrega o banco de dados
            $CI->load->model('dashboard_model');
            $vf =  $CI->dashboard_model->contarVendasFuncionarios();

           return $vf; //retorna a quantidade de registros
       }

       function pd()
       {
            // Obter uma referência ao objeto do controlador
            $CI = get_instance();
           //carrega o banco de dados
            $CI->load->model('dashboard_model');
            $pd =  $CI->dashboard_model->contarNovosPedidos();

           return $pd; //retorna a quantidade de registros
       }

My Main Controller:

class Principal extends CI_Controller {
    
    public function index()
    {           
          //Notificações gerais do painel
          $data['np'] = np();//contar NF pendentes 
          $data['pd'] = pd();//contar os pedidos novos
          $data['vf'] = vf();//contar vendas 
          $total =  pd() + vf() + np();//somar todos
          $data['total'] =  $total;//exibir o valor total

          $this->load->view('admin/template/home', $data);
    }
    
}

My view:

<!--Aqui exibo os resultados nas divs-->
 <li class="nav-item dropdown" >
        <a class="nav-link" data-toggle="dropdown" href="#">
          <span class="badge badge-warning navbar-badge"><?php if (isset($total))  { if($total != "0")  {   echo $total; } } ?></span>
        </a>
           
          if($pd != "0")  { ?>
          <div class="dropdown-divider"></div>
          <a href="<?php echo base_url() ?>" class="dropdown-item">
            <?php echo $pd ?> Novo Pedido
          </a>
          <?php } ?>
               
          if($vf != "0")  { ?>
          <div class="dropdown-divider"></div>
          <a href="<?php echo base_url('') ?>" class="dropdown-item">
            <?php  echo $vf; ?> Venda
          </a>
          <?php  } ?>

          if($np != "0")  { ?>
          <div class="dropdown-divider"></div>
          <a href="#" class="dropdown-item">
            <?php echo $np ?> Nf Pendente
          </a>
          <?php } ?>

Dai tried an ajax like this to update the pd function:

<script>
 var visualizarPedido = setInterval(function(){
                    $.ajax({
                        url: "<?php echo base_url('principal/index/pd') ?>",
                        cache: false,
                        success: function (html) {
                            $("#dropdown-item").text(html);
                        },
                });
            },2000)
</script>

But so far nothing, if you can help me thank.

  • On console shows some error?

  • No, but it shows nothing.

  • I find it interesting to activate php errors ini_set("display_errors", 1); at the beginning of the code, it may be disabled on the server

  • now it appeared on the console in javascript 404 Page Not Foundthe page you requested was not found. I don’t think you can find my helper

1 answer

0


Well after I’m done cracking my head, I’ll leave my answer in case anyone needs it in the future.

//Atualizar Notificações de Pedidos
        var atualizaNotificacaoPedido = function (tempoParaChecarNovamenteEmSegundos) {
          
              $.ajax({
                  type:"GET",
                  url:"http://[::1]/principal/pedido", 
                  dataType: "json",
                  success: function (resposta){
   
                    if (resposta.erro == 0) {
                  
                       $('.pd').html(resposta.listar_servico);
                       setTimeout(function() { atualizaNotificacaoPedido(tempoParaChecarNovamenteEmSegundos); }, tempoParaChecarNovamenteEmSegundos * 40000);
                       
                    } else{
   
                       alert('Erro ao trazer serviços');
                       setTimeout(function() { atualizaNotificacaoPedido(tempoParaChecarNovamenteEmSegundos); }, tempoParaChecarNovamenteEmSegundos * 40000);
                    }
   
                  },
                  error:function(){
                      console.log(resposta);
                      alert('Erro ao trazer serviços.');
                  }
             });
      }
       
      atualizaNotificacaoPedido(40000);

Dai in my controller I created a json response to pull my select from the database so:

 public function pedido()
    {
        $listar_servico = $this->dashboard_model->contarNovosPedidos();
        
        if ($listar_servico) {  
          
                $retorno['erro'] = 0;
                $retorno['msg']  = 'Pedido consultado com sucesso';
                $retorno['listar_servico']  = $listar_servico;

                header('Content-Type: application/json');
                echo json_encode($retorno);
                exit;

            } else {

                $retorno['erro'] = 60;
                $retorno['msg']  = 'Erro';

                header('Content-Type: application/json');
                echo json_encode($retorno);
                exit;
        }

    }

And my view was like this:

 if($pd != "0")  { ?>
          <div class="dropdown-divider"></div>
          <a href="<?php echo base_url() ?>" class="dropdown-item">
            <span class="pd" id="pd"></span> Novo Pedido
          </a>
      <?php } ?>

The only thing that was still unregulated for me is to control the time in ajax that is very fast, I have tried to put, 40000 and it is still very fast, but if I manage to adjust I tidy here. vlw

Browser other questions tagged

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