samedi 24 janvier 2015

Waiting on AJAX result in main JS function


So .... my main init()Javascript function has these 3 lines:



sarea = GetArea(Uname,UIDfield,Table, document.getElementById("Source").value);
darea = GetArea(Uname,UIDfield,Table, document.getElementById("Destination").value);
alert(sarea);


The GetArea function work as expected, and I use the when/then jQuery technique to wait on the AJAX GET, if I monitor it (alert box) I can see that the value before the return statement is correct. however, in the init code, an alert that comes after the function, and uses it's return is incorrect, I get undefined. In addition if I have all three alert boxes I get the undefined one before the other two alert me with the correct result, so the order in the init() function is what's acting funny.



function GetArea(Uname,UIDfield,Table, sourceID){
var ReqUrl = "http://" +Uname+"http://.cartodb.com/api/v2/sql?q=select ST_Area(the_geom::geography)/1000000 as SA FROM "+Table+" where "+UIDfield+"="+sourceID;
var area;

$.when($.ajax({
async: true,
type: 'GET',
url: ReqUrl,
success: function(data) {
area = data.rows[0].sa;
},
error: function() {
area = null;
}
})).then(function(data) {
return area;});
}


I know that I could set async: false but that isn't in the spirit of AJAX, their has to be a neat way to do this.


Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire