How to make a function run after another? JS (Jquery)

1

I have the following functions:

Gets server data by ajax and saves it to an Array of objects:

function carregaPesquisaTabela(){
	controlLoading();
	$.ajax({
	url: "header.php",
	type: "POST",
	dataType:"json",
	data: {
		'procuraPesquisa' : null
	}
	
}).done(function(data){
		pesquisaObj = data;
		controlLoading();
});

}

Get the Object Array and mount a table. (I will not put all the code because it is not necessary)

function montaTabela(){
	$("#tablePesquisas").empty();
	var linha = "";
	for(i = 0; i<pesquisaObj.length; i++){
  //Monta dados e insere em uma tabela 
	$("#tablePesquisas").html(linha);
  }
}

I call them both as follows:

$("#viewPesquisa").submit(function(e){
e.preventDefault();
carregaPesquisaTabela();
montaTabela();
});

The problem is that the action setsTable (); is happening before the function loadsSearchTable (); being finished, and so the result is not being real.

I saw something about callback but I could not implement it. What to do?

    
asked by anonymous 03.11.2018 / 00:25

1 answer

0

Do you see that function that you declare in .done() of jQuery? That's the callback, the function you pass to jQuery invoking when it gets the result.

What you want is to call montaTabela via done, that is:

function carregaPesquisaTabela(){
    controlLoading();
    $.ajax({
        url: "header.php",
        type: "POST",
        dataType:"json",
        data: {
            'procuraPesquisa' : null
        }

    }).done(function(data){
        pesquisaObj = data;
        controlLoading();
        montaTabela();
    });
}

I'll take advantage to mention one detail: in table you're using .html() to append more rows to your table, but .html() replaces all existing content, what you need is .append() .

- Edit -

Sending your own callback:

In response to the comment, it is also possible to send your own function to be called at the end of AJAX.

function carregaPesquisaTabela(callback){
    controlLoading();
    $.ajax({
        url: "header.php",
        type: "POST",
        dataType:"json",
        data: {
            'procuraPesquisa' : null
        }

    }).done(function(data){
        pesquisaObj = data;
        controlLoading();
        if (callback) { /*se nada for enviado, esse if não é executado*/
            callback();
        }
    });
}

$("#viewPesquisa").submit(function(e){
    e.preventDefault();
    carregaPesquisaTabela(montaTabela);
});
    
03.11.2018 / 00:38