My function is not running on page load

1

I'm having the following problem sirs.

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 request() function the sortTable() function should be executed, but it does not happen, and detail if I open the Chrome console and run the sortTable() / p>

More in detail:

  • The page loads these functions;
  • I click on a link that contains the onClick = request() event, to call the request() function;
  • I should load the click event that is inside the function, which does not happen without opening the Chrome console and calling the function there.
  • What do you guys think?

        
    asked by anonymous 15.09.2018 / 05:16

    2 answers

    2

    You're experiencing a problem with syncing. Remember: AJAX is asynchronous by default. So if we want a function to be called after the request, we have to report this with the ".then" like 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));
        }}).then(function(){
            sortTable();    
        });
    }
    
        
    15.09.2018 / 16:08
    0

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

    That explains a lot.

    Thank you!

        
    17.09.2018 / 03:34