lloiacono
lloiacono

Reputation: 5050

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

Upvotes: 3

Views: 709

Answers (2)

antonjs
antonjs

Reputation: 14318

If you need a complete function, you can't use $.post functions;

you will need to call the $.ajax function directly. You pass an options object that can have "success", "error" and "complete" callbacks.

Instead of this:

$.post(<?=$this->baseUrl('user/parse-kml')?>, parameters, function);

you would use this:

$.ajax({
    url: <?=$this->baseUrl('user/parse-kml')?>,
    type: "POST",
    data: parameters,
    success: successFunction,
    error: errorFunction,
    complete: completefunction

});

There are lots of other options available too. The documentation lists all the options available.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

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);
      })
    });
});

Upvotes: 3

Related Questions