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:

  1. issue http request ($.ajax...)

(at point, since network operation slow, js engine chooses continue executing following lines. comes after response completes.)

  1. runs line alert(lng). @ point, still undefined.
  2. the request responses success/error, run corresponding callback function function(response).... alert inside callback function want.

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -