Single ajax with different outputs that doesn’t work without async

Asked

Viewed 77 times

0

Hello. I have a function with an ajax request inside (that’s the real 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 mistakes to be made 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 treated on the server according to the input.

This ajax suits me for everything, but he has some problems, he needs to be async: false or else it won’t work, because of that variable retorno. It just doesn’t work if it’s not async.

This ajax is the only communication with the server, IE, all the information I want to search or save in BD or in the system itself (is a relatively large system made in PHP) are made through it. The retorno can be true/false, a string or even an integer grid to mount a table in another JS function.

What can I do to not depend on async? Or it’s all wrong?

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 way when I want to externalize ajax data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.