Monday, May 28, 2018

javascript - Return data from jQuery.post AJAX call?



Hi I'm calling this function:



function getCoordenadas()
{

var coordenadas = new Array();
$.post(
'baseUrl('user/parse-kml')?>',
{ kmlName: "esta_chica.kml"},
function(jsonCoord) {
jQuery.each(jsonCoord, function(i, val) {
var latlng = val.split(',');
coordenadas.push(new google.maps.LatLng(latlng[0], latlng[1]));
});
},

'json'
);
return coordenadas;
}


like this:



$(document).ready(function(){
$('.caller').click(function() {

console.log(getCoordenadas());
});
});


So when you click .caller it calls the function gets the data correctly populates the array, but console.log(getCoordenadas()); outputs [].



If I move the array declaration (var coordenadas = new Array();) from the function scope to make it global, when I click .caller for the first time console.log(getCoordenadas()); outputs [], but the second time it outputs the array correctly. Any ideas?



Thanks in advance



Answer



This function works asynchronously. AJAX post is fired and then function returns without waiting for AJAX call to complete. That's why coordenadas array is empty.



When you make it global, the first time it's still empty and by the second time you try, the ajax returned and populated the array. You should restructure your code to use a callback. Something like this:



// definition
function getCoordenadas(callback)
{
var coordenadas = new Array();
$.post(

'baseUrl('user/parse-kml')?>',
{ kmlName: "esta_chica.kml"},
function(jsonCoord) {
jQuery.each(jsonCoord, function(i, val) {
var latlng = val.split(',');
coordenadas.push(new google.maps.LatLng(latlng[0], latlng[1]));
});
callback(coordenadas);
},
'json'

);
}

// usage
$(document).ready(function(){
$('.caller').click(function() {
getCoordenadas(function(coord) {
console.log(coord);
})
});

});

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...