Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return data from jQuery.post AJAX call?

Hi I'm calling this function:

function getCoordenadas()
{
    var coordenadas = new Array();
    $.post(
        '<?=$this->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

like image 595
lloiacono Avatar asked May 20 '26 11:05

lloiacono


1 Answers

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(
        '<?=$this->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);
      })
    });
});
like image 120
Sergio Tulentsev Avatar answered May 22 '26 00:05

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!