How to get variable js from sucess pro php

-1

How to make the latitude variable work? I have tried this and nothing is appearing! In succession la within a variable latitude works, but outside does not want to function, it is empty. How to pass the variable latitude pro php? I have this code below:

$.ajax({
        url:'sigilo.com.br/$ip',
        type:'get',
        dataType:'json',
        success:function(res) {
                latitude = res.lat;
                longitude = res.long;
                cidade = res.city;
                Pais  = res.country


        }

    });

    </script>
<?php
$variavelphp = "<script>document.write(latitude)</script>";
echo $variavelphp;
?>
    
asked by anonymous 13.01.2018 / 19:19

2 answers

1

It turns out that the variable does not yet exist when PHP renders the page. If you look in the console, you will see an error type:

  

Latitude is not defined.

$.ajax({
    url:'sigilo.com.br/$ip',
    type:'get',
    dataType:'json',
    success:function(res) {

        // AQUI A VARIÁVEL É DEFINIDA
        // MAS É TARDE DEMAIS,
        // POIS O PHP JÁ FOI PROCESSADO

        latitude = res.lat;
        longitude = res.long;
        cidade = res.city;
        Pais  = res.country
    }

});

The variable will only have value in the Ajax return, and this will only occur after the page load, when PHP has already done the part of it. And you will not be able to dynamically change this $variavelphp variable because it was created in the backend .

    
13.01.2018 / 20:24
0

You can try php directly

// Pegue o valor via URL
$json = file_get_contents('sigilo.com.br/ip');

// Transforme o resultado em um objeto JSON
$obj = json_decode($json);

// Ou transforme o resultado em um array
$arr = json_decode($json, true);

// Acesse o valor no objeto
$variavelphp = $obj->lat;

// Ou no array
$variavelphp = $arr['lat'];
echo $variavelphp;
    
13.01.2018 / 20:22