Get data json print in real time

0

Hello friends, good night!

I have this code working perfectly so I need it to print the variable type every 5 seconds and they told me that I had to do this with ajax but I do not know how to do it!

  

json

[ {"latitude": "-3.3462, -60.67900"}]
  

php

<?php
    // ler o json
    $file = file_get_contents('json.php');    

  
    $decode = json_decode($file, true);

    
    $ultimo = end($decode);

  ?>

<?php $variavel = $ultimo['latitude'];?>
    
asked by anonymous 14.04.2017 / 07:40

1 answer

1

Yes, you can solve with Ajax / jQuery :

Index.php ):

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script></head><body><divid="DivSaida">
        <!-- VALOR DA VARIÁVEL SERÁ MOSTRADO AQUI -->
        <?php require_once("minhapagina.php"); ?>
    </div>
</body>
<script type="text/javascript">
    $(document).ready(function(){

        minhaUrl = "minhapagina.php"; // CAMINHO DA PÁGINA COM O ECHO

        setInterval(function(){

            $.ajax({
                url: minhaUrl,
                success: function( response ) {
                    $('#DivSaida').html( response );
                }
            });

        }, 5000); // TEMPO PARA ATUALIZAR EM MS (milissegundos)

    });
</script>
</html>

Page with echo of variable ( minhapagina.php):

<?php

$file = file_get_contents('json.php');
$decode = json_decode($file, true);
$ultimo = end($decode);
$variavel = $ultimo['latitude'];
echo $variavel; //MOSTRA EXATAMENTE ESSE VALOR NA PÁGINA PRINCIPAL

?>

I did not change the output of your variable , I just gave a echo ! I left some comments in the code, which I found interesting to change.

    
14.04.2017 / 08:40