How can i use a variable in a function outside the function. The console.log(response) shows that the content is been fetch from the php. The alert(lng) shows undefined. Why? What could be the issue with this script.I have been on it for a while.
below is the script.
var lat;
var lng ;
$.ajax({
type: 'GET',
url: 'getlocation.php',
data: 'param=no' ,
dataType: 'JSON',
success: function (response) {
console.log(response);
lat = response.latitude;
lng = response.latitude;
},
error: function (response){
alert (response);
}
});
alert( lng);
Because the variable lng
is not set when the code runs to the line alert(lng)
.
The Ajax call is async. That means, JS engine goes into the flow:
$.ajax...
)(At this point, since the network operation is slow, so JS engine chooses to continue executing the following lines. It comes back after the response completes.)
alert(lng)
. At this point, it is still undefined
.function(response)...
. Alert inside the callback function will get what you want.