View data in real time

Asked

Viewed 998 times

-1

I am trying to display a data taken directly from my database with this script:

<script>
         setInterval( function contaUser(){
              document.write,("<?php
                   $sql = "SELECT Count(id) as c FROM tb_usuario";
                   $result = $con->query($sql);
                   $row = $result->fetch_assoc();
                    echo $row['c'].' Usuários';
               ?>");
               },2000 );
 </script>

Already includes at the beginning of the file all the connection data and etc... I would like to display this data in a div, "card" style... You could tell me what’s wrong?

  • 2

    Have you heard of server-side and client-side languages? For example, PHP will act on the server side, while Javascript, in this case, will act on the client side. The single how they communicate is by HTTP. Search about it, as it seems that you still lack some concepts basic and necessary.

  • 2

    Friend, you will not be able to run a php code within a javscript scope. What you can do is send an ajax with the data pro php server, do the query, and export the data back to javascript. Then you do the setInterval and update x in x times.

  • Follow this: https://aiocollective.com/blog/auto-refresh-content-after-changes-in-database-ajax/

  • All right, thank you very much!

  • div estilo "card"... how so?

  • Welcome Erick Figueiredo, don’t miss these posts to get good answers https://answall.com/help/mcve

  • A good practice is to accept an answer that may have solved your problem. See how in https://i.stack.Imgur.com/evLUR.png and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

Show 2 more comments

1 answer

0


In javascript call via ajax the PHP page that runs SELECT and returns the desired result showing it in <div id="qqId"></div>.

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div id="qqId"></div>
<script>

$( document ).ready(function() {
    var tempo = 2000; //Dois segundos

    (function selectNumUsuarios () {
        $.ajax({
          url: "selectNumUsuarios.php",
          success: function (n) {
              //essa é a function success, será executada se a requisição obtiver exito
              $("#qqId").text(n);
          },
          complete: function () {
              setTimeout(selectNumUsuarios, tempo);
          }
       });
    })();
});


</script>

selectNumUsuarios.php

<?php
$mysqli = new mysqli("localhost", "USUARIO", "SENHA", "Nome_DB");

/* checa conexão */
if (mysqli_connect_errno()) {
    printf("Conexão falhou: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT id FROM cadastro")) {

    /* determina o número de linhas retornadas */
    $numUsuarios = $result->num_rows;

    printf($numUsuarios." Usuarios");

    $result->close();
}

/* fecha a conexão */
$mysqli->close();
?>
  • 1

    Dear Leo, setInterval will run deliberately, it would be better setTimeout, which "should" be set to run when you finish the Xmlhttprequest request

  • @Guilhermenascimento, well remembered, but do not know what the intention of the AP, I decided to put an OBS on it.

  • Dear Leo, it’s not a question of the intention of the AP, setInterval with asynchronous requests of which you have no idea when you will answer can cause a terrible side effect, because setInterval not expected anything, the problem is in your proposed code.

  • What Guilherme is trying to say is: Instead of doing a setInterval to rotate the ajax, place a setTimeout within the scope of the sucess inside the ajax. So it will only call again when the first request is complete and functional. Otherwise, you may end up sending another request while one is still occurring, which can be summed up in a lot of problems.

  • Valeu Guilhermenascimento e @Máttheus Spoo, resposta editada.

Browser other questions tagged

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