1

I've got AJAX which gets timezone information in a function and I want it to return the result.

I now understand that AJAX is asynchronous so I need to have a callback function. I've looked at examples but I can't wrap my head around it.... I'm not sure where the arguments in my getTimezone() function go if I change that to just take a callback function.

Any help would be appreciated, here's the code:

ztimezone=getTimezone(lat,lng);


function getTimezone( tlat,  tlong) {
                 url = "https://maps.googleapis.com/maps/api/timezone/json?location="+tlat+","+tlong+"&timestamp=1331161200&key=******";  
                 $.ajax({  
                 url: url,  
                 type: "GET",  
                 crossDomain: true,  
                 dataType: 'json',  

                 success: function (data) {  
                    alert(data.timeZoneId); 
                    zdata=((data.rawOffset/60)/60);

                 },  
                 error: function (xhr, err) {  
                     alert(xhr.responseText);  
                 }  
             });
return zdata;                
}
dlofrodloh
  • 1,728
  • 3
  • 23
  • 44
  • callback on success or error .. pass the function names and call them on ajax success or error as per requirement. – Neha Nov 13 '14 at 01:09

1 Answers1

1
function getTimezone(tlat,  tlong, callback) { // <----- HERE
    var url = "https://maps.googleapis.com/maps/api/timezone/json?location="+tlat+","+tlong+"&timestamp=1331161200&key=******";  
    $.ajax({  
                 url: url,  
                 type: "GET",  
                 crossDomain: true,  
                 dataType: 'json',  

                 success: function(data) {  
                    alert(data.timeZoneId); 
                    var zdata = ((data.rawOffset/60)/60);
                    callback(zdata); // <----- HERE
                 },  
                 error: function (xhr, err) {  
                     alert(xhr.responseText);  
                 }  
    });
    // return zdata; // <----- HERE
}

The first line allows you to pass a callback into your function.

The one in the middle calls the callback with the result.

The last one is commented out because you can never return a result from an asynchronous function - you must use a callback (or, equivalently, a promise).

To use it, you would do this:

getTimezone(45, 16, function(zoneData) {
  alert(zoneData); // or whatever
});
Amadan
  • 191,408
  • 23
  • 240
  • 301