I am getting some basic info of the visitor on my site using javascript.
var userinfo = "";
//printing user info
$.get("http://ipinfo.io", function (response) {
alert("IP: " + response.ip);
alert("Location: " + response.city + ", " + response.region);
alert(JSON.stringify(response, null, 4));
userinfo = (JSON.stringify(response,null,4)); //saving json in js variable (not working, it says undefined)
}, "jsonp");
Then I want to access this value in my PHP variable:
<?php
echo $getuserinfo ; // How to store JS var here in this php var?
?>
The JS variable value is not being saved, what I am doing wrong? And how can I store JS variable value in PHP variable?
You could make a stat page/api that you make a ajax call to from javascript.
$.ajax({
type: "POST",
url: '/setstats.php',
data: {userdata: userinfo},
success: function(){
console.log("Userdata send");
},
dataType: "json"
});
This will first be avalible at a later time then when the page initally loads, but you could now have it saved in the session for the next requests.
You are using jQuery.get
method.
This method support a parameter called Data
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
After it is sent to the server to http://ipinfo.io
it is available in the called script (index.php or what you have as default) in the $_GET
array.
If you send data: {var1: value1, var2: value2}
you will have $_GET["var1"] and $_GET["var2"]
Simply send data: userinfo
and in php do a var_dump($_GET)
and check what you got
I solved it by using the PHP version of the API:
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
//echo $ip;
return $details;
}
$details = ip_details($userIp);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.