Search code examples
jqueryjsonjquery-mobileasynchronousjquery-callback

jQuery mobile: Wait until $.getJSON is finished


I want to populate a table with $.getJSON call:

$.getJSON("localhost/url",
function (data) {
    $.each(data.reporting_list.reporting, function (i, item) {
        rows = '<tr><td>' + item.data1 + '</td><td>' + item.data2 + '</td></tr>'
    });
    $('#aaa').append(rows);
});

After populating I want to fire some page changes:

$.mobile.changePage("#homePage");

But the page changes before $.getJSON completes.
I want to change the page only after $.getJSON is complete and show ajaxloader instead.


Solution

  • Do

    $.getJSON("localhost/url", function (data) {
        $.each(data.reporting_list.reporting, function (i, item) {
            rows = '<tr><td>' + item.data1 + '</td><td>' + item.data2 + '</td></tr>'
        });
        $('#aaa').append(rows);
        //move to the page in the callback itself
        $.mobile.changePage("#homePage");    
    });