How to update number of users online with PHP + jQuery

Asked

Viewed 112 times

0

I have a file called processa_vis.php where brings the result of all ID with online status, until then all right and usually displays users online on the screen where I call the function.

However I would like you to update the page but only the text where displays the number of users online. I basically include the.php process.php file with include and then call the $result variable where the number of online users is stored within the process.php, I wanted to update this result every 5 seconds.

I saw in some places use jQuery with setInterval but I have no experience with jQuery. It seems to be too simple but several failed attempts.

Archives:

parse_vis.php

<?php
include_once("conexao.php");

$query = "SELECT * FROM usuarios WHERE status_online = 'S';";
$sql = mysqli_query($conn, $query);
$result = mysqli_num_rows($sql);

echo $result;

?>

index php.

<?php
session_start();
include("conexoes/conexao.php");
if($_SESSION["id"]){
    header("location: painel.php");
}
?>
<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <title>Banco de Dados - Login</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container">
                <a class="navbar-brand" href="#">Banco de Dados</a>
            </div>
        </nav>
        <div class="container">
            <h4 class="mt-4 display-4 text-center">Área de Login</h4><hr>
            <div class="col-md-6 offset-md-3 mt-5">
                <form method="post" action="conexoes/login.php" class="p-3" style="background-color: #e4e4e4; border-top: 20px #999999 solid;">
                <?php
                    if(isset($_SESSION['msg'])){
                        echo "<div class='col-md-6 offset-md-3'>";
                        echo $_SESSION['msg'];
                        unset($_SESSION['msg']);
                        echo "</div>";
                    }       
                ?>
                    <div class="form-group">
                        <div class="col-md-6 offset-md-3">
                            <label for="inputLogin">Login</label>
                            <input class="form-control" name="login" id="InputLogin" placeholder="Usuário">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-6 offset-md-3">
                            <label for="InputSenha">Senha</label>
                            <input type="password" class="form-control" name="senha" id="InputSenha" placeholder="Senha">
                        </div>
                    </div>
                    <div class="col-md-6 offset-md-3">
                        <button type="submit" id="btnLogin" class="btn btn-block btn-primary">Entrar</button>
                    </div><br>
                    <span>Ainda não possui uma conta?</span><br>
                    <small class="text-muted"><a href="cadastrar.php">Crie uma aqui.</a></small>
                </form>
            </div>
            <div id="qtd_usuarios_online"></div>
            <div class="footer" style="margin-top: 20px; margin-bottom: 10px;"><hr>
                <footer>
                    <p class="text-muted text-center">&copy 2019</p>
                </footer>
            </div>
        </div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

        <script>

        $(document).ready(function(){ // iniciar assim que o documento estiver carregado
        setInterval(update_visitas(),5000); // vai rodar a função a cada 5000 milésimos (5 segundos)
        function update_visitas(){ //função que será carregada
            $.ajax({url: "conexoes/processa_vis.php", // ajax que vai carregar o arquivo PHP
                cache: false, // remover cache caso haja
                success: function(result){ //se carregar com sucesso, carrega os dados do PHP
        $('#qtd_usuarios_online').html(result); //exibe dentro da DIV #qtd_usuarios_online a saída do PHP
        }});
        }
        });

        </script>

    </body>
</html>
  • Can you put some of those failed attempts to see where you’re struggling?

  • I don’t have it here because I erased all attempts

  • But I modified and put the basic code in the files

2 answers

1

in the first place, what you really need is to have a reverse communication with the server, using for example Nodejs, in this way, the server warns by broadcast the "news", in your case, the amount of visitors.

But it is also possible to do with jquery in a way, more or less like this:

  1. Whenever you use Jquery, you need to add the library. You can download it or use a CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

  1. You will call from time to time via Ajax your PHP file and display your content in a div, thus:

HTML DO INDEX.PHP

<div id="qtd_usuarios_online"></div>

Jquery at the bottom of the page

    <script>

$(document).ready(function(){ // iniciar assim que o documento estiver carregado

setInterval(update_visitas(),5000); // vai rodar a função a cada 5000 milésimos (5 segundos)

function update_visitas(){ //função que será carregada

$.ajax({url: "processar_visitas.php", // ajax que vai carregar o arquivo PHP
        cache: false, // remover cache caso haja
        success: function(result){ //se carregar com sucesso, carrega os dados do PHP

$('#qtd_usuarios_online').html(result); //exibe dentro da DIV #qtd_usuarios_online a saída do PHP

}});  

}
});

</script>
  1. We need to change your process.php a little to display visits:

    include_once("conexao.php");
    
    $query = "SELECT * FROM usuarios WHERE status_online = 'S';";
    $sql = mysqli_query($conn, $query);
    $result = mysqli_num_rows($sql);
    $usuarios_online = $result;
    echo $usuarios_online; /*vai exibir a variável como resultado do processamento em ajax */
    
  • I did exactly the way you instructed me and I was unsuccessful, the numbers don’t update themselves, only if I refresh the page.

  • Hi @Carlospereira, are you using Chrome? Check in the "Console" tab of inspecting Elements if you are returning an error in ajax, use console.log if necessary to print the steps and anything warns me, abs

  • No error in console

  • I edited and entered the whole code into the question, so maybe it’s better to solve this problem. ( ignores the visual errors of the site, I only create the bootstrap to not dry the study of improvement in php )

  • Carlos, try in your process_vis.php to put an echo "test"; for example to see if you print the test word in HTML, if so, the problem is in processing PHP or Sqls

  • I did what you said and returned the word I entered in process_vis.php. When I soon on the site with some account appears the number " 1 ", "2 " so on only if I update the page manually

Show 1 more comment

0

You can try something like:

<div id="output"></div>
<script>
$(document).ready(function() {
    setInterval(function()
        $.ajax({
             url:'processar_visitas.php',
             type: "post",
             complete: function (response) { // ou success
                  $('#output').html(response);
             },
             error: function () {
                  $('#output').html('Aconteceu alguma coisa errada!');
             },
        });
    }, 5000);
});
</script>

parse_visits.php

<?php
    include_once("conexao.php");

    $query = "SELECT * FROM usuarios WHERE status_online = 'S';";
    $sql = mysqli_query($conn, $query);
    $result = mysqli_num_rows($sql);
    echo $result;
?>
  • I didn’t succeed either, your code doesn’t even display the number :/

Browser other questions tagged

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