Ajax + Php Pass Variable

Asked

Viewed 487 times

0

How can I send a variable through Ajax and recover 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 the Ajax run from time to time, send to the variable $logado that is in the PHP.

I know if I wear one include works but I need time on time via Ajax to always have the variable updated.

  • Be more specific in your question. You are passing which variable to where? You could put the code of "contalog.php" in the body of the question?

  • Paul, consider clicking the "edit" button and adding this information to the question. Getting clearer, we can help you better. I’m pretty sure you’re gonna need a "long Polling"

  • @Wallace Maxters Feito !

  • @Wallace Maxters How Can I Solve ?

  • I answered your question, see if it helps :D

1 answer

2


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

First of all, you’d have to change his code for him to use setTimeout with recursion, instead of using setInterval, on account 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 file contalog.php, you must convert the output to the format JSON 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();
  • @ Wallace Maxters OK I’ll add the lines in the contalog.php and change the js script , but I didn’t understand this part First, you’d have to change your code to use setTimeout with recursion, instead of using setInterval

  • Ajax will give me the variable and I can use it directly in php with an echo ?

  • @Paulomaia knows why she needs to change setInterval to setTimeout? is the following... in my logic, the "log" function is executed right away. When sucess is called, it executes the same function after 1000 with setTimeout, when it reaches Success it will run again, because it executes itself. The problem with setInterval is that if the request takes more than 1 second, it will run twice, creating a disorder in the timing of ajax executions.

  • @Paulomaia you need to understand the following: When I did the echo json_encode(...), you are saying pro PHP print the value of the variable in JSON format (the Javascript that runs AJAX will understand in success that this variable is in the formed Javascript and interpret it correctly). Without this, there is no way the two languages communicate, they have different behaviors and functionalities.

  • Yes, but outside of ajax I need to use the updated variable $logged in, I’m going to give a <?php echo $logged in; ?>

  • @Paulomaia I think you’re making a big mess. Where you want to use the variable $logado "ajax time"? You could just declare a javascript function and call it in the snippet where I put a comment "your logic here"...

  • YES, ajax runs the script and I need the value returned to use in php, Scupe if I’m not making myself clear.

  • I edited the answer. See if this makes understanding logic easier.

  • $log returns a number that can be 0 or ...

  • @Wallacemaxters, suddenly it would not be the case to receive one push? Using [tag:Firebase] on the client side?

Show 6 more comments

Browser other questions tagged

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