javascript - using a variable outside a function in ajax -
how can use variable in function outside function. console.log(response) shows content been fetch php. alert(lng) shows undefined. why? issue script.i have been on while.
below 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 variable lng
not set when code runs line alert(lng)
.
the ajax call async. means, js engine goes flow:
- issue http request (
$.ajax...
)
(at point, since network operation slow, js engine chooses continue executing following lines. comes after response completes.)
- runs line
alert(lng)
. @ point, stillundefined
. - the request responses success/error, run corresponding callback function
function(response)...
. alert inside callback function want.
Comments
Post a Comment