How to get variable js from sucess pro php

Asked

Viewed 42 times

-1

How do I make the latitude variable work ? I tried this and nothing is appearing! In sucess la inside the latitude variable works, but on the outside it does not want to work, it is empty. How to pass the latitude variable 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;
?>

2 answers

1

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

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 on the return of Ajax, and this will only occur after loading the page, when PHP has already done its part. And even you won’t be able to dynamically change this variable $variavelphp because she was raised in back-end.

  • ai did not understand , :(

  • @Denyprogramadorbom When PHP loads the page, the variable latitude there is no. After loading the page, Ajax will be executed and create the variable, but then that’s it, because PHP already did the part of it that was just load the page.

  • Oxenteee javascript does not run while loading with php?

  • @Denyprogramadorbom Ajax does not return the value together with the page load, only after.

  • @Denyprogramadorbom When the page is loaded, Ajax will still search the page sigilo.com.br/$ip the value to define the variable latitude.

  • But javascript loads together with php right

Show 1 more comment

0

You can try doing it right in php

// 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;

Browser other questions tagged

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