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

Asked

Viewed 33 times

1

I have the following functions:

Grab server data by ajax and save to an object array:

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

}

Grabs the Object Array and mounts a table. (I won’t put all the code because it’s 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 montaTable(); is happening before the function loadPesquisaTable(); is finished, and so the result is not being real.

I saw something about callback but I couldn’t implement it. What to do?

1 answer

0


Are you seeing that function you declare in .done() jQuery? That’s the callback, the function you pass to jQuery to invoke when it gets the result.

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

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

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

I will take this opportunity to mention a detail: in montaTable you are using .html() to attach 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, 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);
});
  • So what I happen is that I wanted my function to chartPesquisaTable(), could be called to fetch the data and another function to treat them, for example, put them in a table or in an option of a select. And avoid having to duplicate the server search code.

  • Okay, try the fix I made.

  • Great! Exactly what I needed. Working perfectly! Thank you!

Browser other questions tagged

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