Search code examples
javascriptjquerygetjson

getJSON running priority


I'm trying to get some data from server which is in JSON format. I want to show them in a table that is dynamically created. When I run this code, no errors appear and also it gets data correctly but it shows nothing in the table. I think there is a running priority issue but I don't know how to fix it.

$.getJSON(getUrlPizza, function(result) {
    keepGetData = result;
    var j, k = 0;
    $.each(keepGetData, function(i, field) {
        getUrlSize = urlSize + "/" + keepGetData[i].id;
        $.getJSON(getUrlSize, function(resultS) {
            size = resultS;
            $.each(size, function(s, fieldS) {
                sizes[k] = size[s];
                console.log(sizes[k]);
                k++;
                ///////
                ////// Create Table
                /////
                out += "<tr><td>" +
                    keepGetData[i].name +
                    "</td><td>" +
                    fieldS.size1.name +
                    "</td><td>" +
                    fieldS.price +
                    "</td><td>" +
                    "<button onclick='edit(this)'>Edit</button></td><td>" +
                    "<button onclick='removeItem(this)'>Remove</button></td></tr>";
                //////
                /////
                ////
            });
        });
    });
    out += "</table>";
    document.getElementById("drinkConDiv").innerHTML = out;
    $("#add").show();
    $("#back").show();
});

Solution

  • TRy this: you are executing a asinc call you need to append the html when the call is completed

     $.getJSON(getUrlPizza, function(result){
            keepGetData = result;
            var j,k =0;
            $.each(keepGetData, function(i,field){
            getUrlSize = urlSize + "/" + keepGetData[i].id;
            $.getJSON(getUrlSize, function(resultS){
                size = resultS;
                $.each(size, function(s,fieldS){
                    sizes[k] = size[s];
                    console.log(sizes[k]);
                    k++;
                    ///////
                    ////// Create Table
                    /////
                    out +=  "<tr><td>"+ keepGetData[i].name + "</td><td>"+ 
                            fieldS.size1.name + "</td><td>"+  
                            fieldS.price + "</td><td>"+ 
                            "<button onclick='edit(this)'>Edit</button></td><td>"+
                            "<button onclick='removeItem(this)'>Remove</button></td></tr>";
    
                            $"#drinkConDiv").html("<table>"+out+"</table>");
                            $("#add,#back").show();
    
                    //////
                    /////
                    ////
                });
            });
            });
    
        });