79457887

Date: 2025-02-21 15:38:21
Score: 2.5
Natty:
Report link

My Hostinger plan doesn't allow me to add websockets. So it wouldn't be productive for me to hire another server just for this.

I tried using AJAX, but it stopped working overnight. I don't know what could have happened, but now it doesn't even run the tests of writing to the screen with "script"

My code with AJAX:

<?php
    //OPÇÃO DE SELECIONAR ATENDIMEENTO PARA A CONVERSAR OU DE VINCULAR A UMA PESSOA CRIANDO NOVO ATENDIMENTO

    //COLUNA DA CONVERSA
        echo "<div class='col-md-6'>";

            // MENSAGEM AZUL É DO NUMERO DA META, UM SUPORTE ATENDENDO UM CLIENTE (SEND MESSAGE)
                // $_SESSION['messages']
            // MENSAGEM CINZA É DO CLIENTE, UM CLIENTE RESPONDENDO A META (WEBHOOK)

            set_time_limit(0); // Permite execução infinita

            include_once ("../webhook/db_connection/functions.php");
            include ("../whatsapp/functions.php");
            $dotenvPath = __DIR__ . '/../webhook/controllers/.env';
            if (file_exists($dotenvPath)) {
                $dotenv = fopen($dotenvPath, 'r');   // Carrega variáveis de ambiente do arquivo .env
                if ($dotenv) {
                    while (($line = fgets($dotenv)) !== false) {
                        putenv(trim($line));
                    }
                    fclose($dotenv);
                }
            } else {
                file_put_contents('php://stderr', "Arquivo .env não encontrado\n");
            }

            //$numeroCliente = '553193926517';  // Número do cliente
            $numeroCliente = $_GET['wa_from'];  // Número do cliente
            // Obtenha as mensagens iniciais
            $mensagens = buscarMensagensChat($conexao, $numeroCliente);
            $ultimoIdMensagem = buscarUltimoIdMensagemRecebida($conexao, $numeroCliente);
            //var_dump($ultimoIdMensagem);

            // --------------------------------------------------- Vincular a mensagem pendente ao usuario que abriu a mensagem
            

            ?>
            
            <!-- ------------------------------------------------- Script pra recarregar a pagina quando receber uma nova mensagem -->
            <script>
                console.log("Último ID da mensagem (JS):", ultimoIdMensagemJS);
                saida.innerHTML += "<br>Verificando novas mensagens...<br>";
                
                let ultimoIdMensagemJS = <?php echo json_encode($ultimoIdMensagem); ?>;
                console.log("Último ID da mensagem (JS):", ultimoIdMensagemJS);

                
                function recarregaPagina() {
                    const saida = document.getElementById('saida');
                    saida.innerHTML += "<br>Verificando novas mensagens...<br>";
                    saida.innerHTML += `<br><strong>Ultimo Id da mensagem:</strong> ${ultimoIdMensagemJS}<br>`;

                    fetch(`../whatsapp/msg.php?acao=executar&ultimoIdMensagemJS=${ultimoIdMensagemJS}&numeroCliente=${numeroCliente}`)
                        .then(response => {
                            saida.innerHTML += `<br><strong>response:</strong> ${response}<br>`;

                            // Verificar o status da resposta
                            if (!response.ok) {
                                throw new Error(`Erro na resposta do servidor: ${response.status}`);
                            }
                            return response.json(); // Converte a resposta em JSON
                        })
                        .then(data => {
                            //saida.innerHTML += `<br><strong>data:</strong> ${data}<br>`;
                            // Exibir a resposta do servidor na página
                            //saida.innerHTML += `<br><strong>Resposta do servidor:</strong> ${JSON.stringify(data)}<br>`;

                            if (data.recarregar) {
                                ultimoIdMensagemJS = data.novoUltimoIdMensagem;
                                //saida.innerHTML += `<p>Nova mensagem detectada! Recarregando a página...</p>`;
                                // Recarrega a página
                                //setTimeout(() => {
                                    location.reload(); // Recarrega a página
                                //}, 10000); // 5000ms = 5 segundos
                            } else {
                                //saida.innerHTML += `<p>Sem novas mensagens.</p>`;
                            }
                        })
                        .catch(err => {
                            // Imprimir o erro diretamente na página
                            //saida.innerHTML += `<p>Erro ao chamar a função: ${err.message}</p>`;
                        });
                }
                
                setInterval(recarregaPagina, 3000);     // Chama a função a cada 3 segundos
            </script>

            <?php

            // CORPO DA PÁGINA - <!-- Main content -->
            echo "<section class='content'>";
                echo "<div class='container-fluid'>";
    ............................... code +
Reasons:
  • Blacklisted phrase (1): não
  • RegEx Blacklisted phrase (2): encontrado
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Mares