Update a PHP variable within JavaScript in a time interval [duplicate]

-3

We have a postgresql query inside a javascript function which is as follows:

function  valor(){  
    <?php 
        $con_string = "host='ip' port=numero dbname='banco' user='usuario' password='***'";
        $conn = pg_connect($con_string);
        $query="SELECT tubeteira from velocidadereal";
        $output=pg_query($conn,$query);
        $retorna =  pg_fetch_array($output);
        $valor = $retorna["tubeteira"];
    ?>

    return <?php echo $valor ?>;
} 

setInterval(valor,1000);

But although it updates every 1 second the variable php is not updating in the function, so when changing the value in the database of the column where we are performing the select it does not return the new value unless we refresh the page.

How can I get it to update automatically?

It's important to note that the query is feeding a chart.

    
asked by anonymous 06.07.2018 / 15:52

1 answer

4

PHP is a server-side language (which works alongside the server). Javascript is a client-side language (which works on the client side.)

You can not execute a Javascript function expecting this to affect the behavior of a PHP variable. This is how to expect a "magic to happen".

The solution that you can apply in such cases are numerous, but here I will mention one of them:

  • Request X's AJAX request in X periods.
  • Use a Websocket

An example of how to do with AJAX:

  • Create a PHP script to return the data in JSON.
  • Code:

    $con_string = "host='ip' port=numero dbname='banco' user='usuario' 
    password='***'";
    $conn = pg_connect($con_string);
    $query="SELECT tubeteira from velocidadereal";
    $output=pg_query($conn,$query);
    $retorna =  pg_fetch_array($output);
    $valor = $retorna["tubeteira"];
    
    
    header('Content-Type: application/json');
    
    exit(json_encode(['valor' => $valor]));
    

    Create a Javascript function that requests through AJAX:

     function valor(valor) {
         // faça alguma coisa como  valor obtido de 1 em 1 segundo
     }
    
    setInterval(function atualizarValor() {
    
        if (atualizarValor.executando) return;
    
        atualizarValor.executando = true;
    
         $.ajax({
             url: '/script_json.php',
             success: function (response) {
    
                valor(response.valor);
    
                atualizarValor.executando = false;
             }
         }) 
    }, 1000);
    

    Note : Be aware of the number of requests made on your server, as this can degrade your performance depending on the number of concurrent X requests.

        
    06.07.2018 / 17:10