1

Hello guys this is my very first post in this forum.

I have this function

function TestePresenca(){
var msg = ''
$('#teste tbody tr').each(function(){
    var MemberId;
    var ClassId;
    var PresenceDate;
    var OClasse;

    var DataPre = $('#data_presenca').val();
    var TotBiblia = $('#tot_biblia').val();
    var TotOferta = $('#tot_ofertas').val();

    $(this).find('td').each(function(){
        if($(this).index() == 0){
            MemberId = $(this).text();
        }

        if($(this).index() == 3){
            $(this).closest('tr').find("select").each(function(){
                ClassId = this.value;
            })
        }

        if($(this).index() == 4){
            OClasse = $(this).text();
        }           
    });

    $.ajax({
        type: 'POST',
        url: BASE + '/save_list_presence',
        data: {pMemberId: MemberId, pClassId: ClassId, pOClasse: OClasse, pDataPre: DataPre, pTotBiblia: TotBiblia, pTotOferta: TotOferta},
        success: function(retorno){
            msg += retorno;
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('Erro!');
        }
    });
});
alert(msg);}

My problem is the "alert(msg)" fires without a message, in debug time I see its fire then the each and ajax execute after and the "msg" variable are pupulated at the end, but the alert was fired before.

Anyone have any idea how can I fix it?

Thanks in advance.

2 Answers2

0

AJAX is asynchronous - the code below it may run before the AJAX call finishes.

-1

Try to use this async: false in your ajax call:

$.ajax({
        type: 'POST',
        url: BASE + '/save_list_presence',
        async: false,
        ...

From the jQuery.ajax() API Docs

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

palaѕн
  • 72,112
  • 17
  • 116
  • 136