MFKGER MFKGER - 6 months ago 14
JSON Question

Storing API data in global variables jquery

var position= $.getJSON( "http://ip-api.com/json", function( data ) {
position = {lon: data.lon, lat: data.lat}
return position;
});
var lon = position.lon;
var lat = position.lat;
console.log(lon);


How can I getvariables from async functions to become global?

Answer

Try this, this is work good way

window.onload = function() {
set();
setTimeout(get,2000);;
};
function set() {
$.getJSON( "http://ip-api.com/json",function(data) {
var position = {"lon": data.lon,"lat": data.lat};
document.getElementById("id").value= position;
});
}
function get() {
var k = $("#id").val();
console.log(k);

}
Comments