Take the JSON return and move to a PHP variable

Asked

Viewed 433 times

0

I need to pass the return variable inside the alert and move on to PHP, but everything I’m trying from examples to here, even from the forum, is giving Javascript error:

<?php
 $pegar_ip = $_SERVER["REMOTE_ADDR"];
?>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 

<script>
  $(document).ready(function() {
        $.getJSON("https://ipinfo.io/<?=$pegar_ip;?>/json", function(dados) {              

            alert (dados.loc);

        });
  });
</script>

3 answers

2


Try using file_get_contents see how it looks:

<?php
    $pegar_ip = $_SERVER["REMOTE_ADDR"];

    $json_url = "https://ipinfo.io/".$pegar_ip."/json";
    $json     = file_get_contents($json_url);
    $json     =str_replace('},

        ]',"}

        ]",$json);
        $data = json_decode($json, true);

        echo "<pre>";
        print_r($data);
        echo "</pre>";

The data will be inside the variable $data

  • Dusty solution @Samuel, thank you!!!!

1

I suggest you use CURL follows my sample code:

<?php

	$url = "https://api.ipify.org/";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$ip = curl_exec($ch);
	curl_close ($ch);


	$url = "https://ipinfo.io/".$ip."/json";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	print $server_output = curl_exec($ch);
	curl_close ($ch);
?>

0

PHP and Javascript can’t communicate, so I suggest you try making one innerHTML with the variable within a input and then use $_GET or $_POST to pull you into PHP.

<script type="text/javascript">
 function teste()
 {
     var teste = 5;
     document.GetElementById("variavel").innerHTML ='<input type="hidden" name="valor" value="'+teste+'">'; 
 }
<body>
<form>
<div id="variavel">
</div>
</form>

 <?php
    $varTeste=$_GET['valor'];
 ?>

Browser other questions tagged

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