Ajax + Php Pass Variable

0

How can I send a variable through Ajax and retrieve the value in PHP?

<script type="text/javascript"> 
setInterval(function(){
$.ajax({
async: true,
url: 'contalog.php',
dataType: 'html',
type: 'POST',
cache: false,
success: function(result){ 
// mandar a variavel $logado que vem do arquivo requisitado aqui acima ....
} 
}); 
}, 1000); 
</script>

And use it like this in my PHP, ...

echo $logado;

I need to Ajax run from time to time, send it to the $logado variable that is in PHP .

I know if I use a include it works but I need time to time via Ajax to always have the variable updated.

    
asked by anonymous 11.11.2017 / 03:50

1 answer

2

If you need to check from time to time, consider using Long Polling to do it.

First, you would have to change your code to use setTimeout with recursion, instead of using setInterval , because of the problems described in that question

(function log() {


    $.ajax({
        url: 'contalog.php',
        type: 'POST',
        success: function(result) { 

            // A variável retornada pelo "contalog.php"
            verificarLogado(result.logado);

            // Só executa no caso de success:
            setTimeout(log, 1000);
        } 
    }); 

})(); 

function verificarLogado(logado) {
    if (logado) {
      alert('Está logado');
    } else {
      alert('Não está logado');
    }
}

In your contalog.php file, you should convert the output to JSON format and use the correct header for browser recognition:

 #Trecho do código do AP postado no PASTBIN
 // Seleciona da tabela
$sql = "SELECT * FROM logado WHERE hora > :hora GROUP BY ip";
$sql = $pdo->prepare($sql);
$sql->bindValue(":hora", date('H:i:s', strtotime("-2 minutes")));
$sql->execute();
$logado = $sql->rowCount();

// Trecho importante

header('Content-Type: application/json');

echo json_encode(['logado' =>  $logado]);

exit();
    
11.11.2017 / 04:37