Single Ajax with different outputs that does not work without async

0

Hello. I have a function with an ajax request inside (this is the actual function):

function carregaAjax(caminho,tabela,funcao,dados){
    dados.push({name:"funcao", value:funcao});
    dados.push({name:"tabela", value:tabela});
    var retorno;
    $.ajax({
        url: caminho,
        type: 'post',
        dataType: 'html',
        data: dados,
        async: false
    })
    .done(function(res) {
        var resposta = JSON.parse(res);

        if($.isArray(resposta)){
            retorno = resposta;
        }
        else if(resposta == 1){
            retorno = resposta;
        }
    })
    .fail(function(res) {
    })
    .always(function() {
    });
    return retorno;
}

There are some errors to be written in .done according to what will be returned, so ignore. The data:dados will always be an array with everything I need, and this is handled on the server according to the input.

This ajax caters to everything, but it has some problems, it needs to be async: false or it will not work, because of that retorno variable. It just does not work if it's not async.

This ajax is the only communication with the server, that is, all the information I want to fetch or save in the DB or on the system itself (it's a relatively large system done in PHP) is done through it. The retorno can be true / false, a string or even an entire grid to mount a table in another JS function.

What can I do to not depend on async? Or is everything wrong?

    
asked by anonymous 09.02.2017 / 19:06

1 answer

0

Good afternoon!

Try as in the example below:

var ajaxData = {
     categoria:  'produtos',
     consulta:   'exibirProduto',
     codProduto: $('#produtoFieldCodProduto')
};

var meuAjax = function (fn) {
    $.ajax ({
      type: 'POST',
      data: ajaxData,
      url:  'http://localhost/webService/',
      error: function (error) {
          console.log(error);
      },
      success: functions (jsonData) {
          fn (jsonData);
      }
    });

The data you can recover as follows in any context within the script:

meuAjax (function (json) {
    console.log (json); // resposta
});

I always do this when I want to output ajax data.

    
09.02.2017 / 19:35