Return data from jQuery.post AJAX call?

Hi I am 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 hit .caller it calls the function that gets the data, fills the array correctly, but console.log (getCoordenadas ()); outputs [].

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

Thank you in advance

+3


source to share


2 answers


This function works asynchronously. The AJAX message is triggered and then the function returns without waiting for the AJAX call to complete. Therefore the array is coordenadas

empty.

When you make it global, the first time it is still empty and the second time you try, ajax returned and populated the array. You have to rearrange your code to use the callback. Something like that:



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

      

+3


source


If you want a complete function, you cannot use functions $.post

;

you will need to call the function $.ajax

directly. You are passing an options object, which can have "success", "fail", 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 many other options available. The documentation lists all the options available.

+1


source







All Articles