My function is not running on page loading

Asked

Viewed 48 times

1

I’m having the following problem.

I have the following function

function sortTable() {
arr = JSON.parse(localStorage.context_data);
    $('#tableLemos th').click(function () {
        console.log("funcao carregada...")
        var id = $(this).attr('id');
        var asc = (!$(this).attr('asc')); // switch the order, true if not set

        // set asc="asc" when sorted in ascending order
        $('#tableLemos th').each(function () {
            $(this).removeAttr('asc');
        });
        if (asc)
            $(this).attr('asc', 'asc');

        sortResults(id, asc);
    });
}

and also this

function request(url) {
dados = [];
$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    //url: "http://localhost:8080/WEB/web/configFields/" + field,
    url: url ? url : "http://localhost:8080/WEB/web/usuarios/find/",
    dataType: "json",
    success: function (data) {
        dados = data;
        localStorage.setItem("context_data", JSON.stringify(data));
        transform_table(JSON.stringify(data));
    }});
sortTable();
}

As a rule, every time I call the function request() the function sortTable() should run, but it doesn’t, and detail if I open the Chrome console and run the function sortTable() there works.

In more detail:

  1. The page loads these functions;
  2. I click on a link that contains the event onClick = request(), to call the function request();
  3. You should load the event click which is within the function, which does not happen without me opening the Chrome console and calling the function there.

What do you think?

2 answers

2


You have a problem related to lack of timing. Remember: AJAX is asynchronous by default. Therefore, if we want a Function to be called after the request, we have to inform this with the ". then" in this way:

function request(url) {
dados = [];
$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    //url: "http://localhost:8080/WEB/web/configFields/" + field,
    url: url ? url : "http://localhost:8080/WEB/web/usuarios/find/",
    dataType: "json",
    success: function (data) {
        dados = data;
        localStorage.setItem("context_data", JSON.stringify(data));
        transform_table(JSON.stringify(data));
    }}).then(function(){
        sortTable();    
    });
}

0

Hhmm understood friend, that means at the moment I call my request() function the Ajax code runs simultaneously with the right function?

That explains a lot.

Thank you!

Browser other questions tagged

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