DELETE me
DELETE me

Reputation:

how to declare variable in javascript

$("#btnsub").click(function () {
    var add = $("#txtname").val();

    var obj;
    var geo = new google.maps.Geocoder;
    geo.geocode({ 'address': add }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            obj = results[0].geometry.location;
            obj = convert(obj);
            alert(obj);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
    alert(obj);
  // why this alert run first instead of the upper alert()
});

Upvotes: 0

Views: 442

Answers (3)

user113716
user113716

Reputation: 322502

If geo.geocode() is an AJAX request, then the code that comes after it does not wait for the response to return before it executes.

As such, the code runs out of order. The second alert() fires, because there's nothing to prevent it from firing. The first one fires when the AJAX response is received.

If you have some other code that relies on the response, then place that code in a function, and call it from inside the callback for geo.geocode().

 $("#btnsub").click(function () {
            var add = $("#txtname").val();

            var obj;
            var geo = new google.maps.Geocoder;
            geo.geocode({ 'address': add }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    obj = results[0].geometry.location;
                    obj = convert(obj);
                    alert(obj);

                    // Call a function that relies on the response
                    //   and pass the obj to it.
                    someOtherFunction( obj );
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        });

function someOtherFunction( data ) {
    alert( data );
    // do something with the obj (referenced as data)
}

Upvotes: 3

SLaks
SLaks

Reputation: 887449

The geocode function is asynchronous.

The callback that you pass it runs some time after the call to geocode; the geocode function itself does not (and cannot) wait for a response.

Upvotes: 4

meder omuraliev
meder omuraliev

Reputation: 186562

Probably because the other one is in a callback? It depends on what .geocode does with it, but most likely it could be an ajax callback.

Upvotes: 0

Related Questions