After many hours searching the internet and Stackoverflow I am no nearer to a solution to the problem I have of passing a piece of JSON data to a javascript variable that will be visible throughout the web page I am trying to construct. I am picking up the JSON data from ipinfo.io. This portion of the activity is working correctly and displays the data on the web page
We use cookies to ensure that we give you the best experience on our website. If you continue to use the site without changing your settings, we'll assume that you are happy to receive all cookies on the site. You can find out more about cookies and how to manage your cookie settings at any time by clicking here .
IP: 87.112.15.241
City: null
Region:null
Country: GB
Hostname: No Hostname
Location: 51.5000,-0.1300
Org: AS6871 PlusNet PLC
Full response:
{
"ip": "87.112.15.241",
"hostname": "No Hostname",
"city": null,
"region": null,
"country": "GB",
"loc": "51.5000,-0.1300",
"org": "AS6871 PlusNet PLC"
}
However what I want to be able to do is keep the country code in a separate variable to enable me to use it later to decide whether I need to apply the European Union rules on cookies or not depending on the country of origin of the viewer.
The javascript is as follows
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3jquery.min.js">
</script>
<script type="text/javascript">
var Country = '';
$.get("http://ipinfo.io", function (response) {
$("#ip").html("IP: " + response.ip);
$("#city").html("City: " + response.city);
$("#region").html("Region:" + response.region);
$("#country").html("Country: " + response.country);
$("#hostname").html("Hostname: " + response.hostname);
$("#org").html("Org: " + response.org);
$("#loc").html("Location: " + response.loc);
$("#details").html(JSON.stringify(response, null, 4));
Country = response.country;
console.log(Country);
}, "jsonp");
console.log(Country);
</script>
The two console.log messagfes are displayed as GB for the first and empty string for the second.
Evidently the use of the variable Country at the top of the script is not being updated by the Country = response.country line of code.
I am, obviously, doing something wrong and would appreciate a little help with this.
So far, none of the previously suggested solutions to this problem do actually result in a value being placed in the correct variable, i. e. the first mention of the Country variable. Whihc is why I opened a new question.