Question

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.

Was it helpful?

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");    
});

OTHER TIPS

Although the answer is already given by Arun P Johny, But I just wanted to make it more clear, the proper usage of $.get() method in jQuery

According to http://api.jquery.com/jQuery.get/#jQuery-get1 The $.get() method is actually

jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

Where The two blocks i.e. data and success will only called when the request is completed, so you can call this function $.mobile.changePage("#homePage"); in either of the block

i.e. in the function (data) { } block, like Arun P Johny suggested or you can call it in any of the other callbacks below.

var jqxhr = $.get("example.php", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });

Like $.ajax() the above callbacks work as success error and complete respectively

Hope this helps

ajaxcall(function(){ $.mobile.changePage("#homePage");});

function ajaxcall(callback){
$.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
    callback();
});

Using callback function also, you can also try this way

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top