Kinshuk Rastogi Kinshuk Rastogi - 5 months ago 26
jQuery Question

how to populate a html table inside a dynamically loaded DIV

i have a DIV container inside a HTML page where I am dynamically loading other HTML pages using jquery.load() function . On one of the pages i need to populate a table from the database just after/before that page loads. How do I call a javascript function that executes just after that DIV is loaded with the page.

this is the dynamically loaded "headquarters.html" page:

<div class="row">
<div class="col-md-10" >
<table class="table table-bordered table-hover" id="tbl_hqlist">
<tr>
<th> HQ Code</th>
<th> Headquarter Name</th>
</tr>
</table>
</div>
</div>


i am loading that page using jquery.load() function like below:

function fn_headquarters(){
$('#bodyContent').load("../html/headquarters.html");
headquarterManagement();
return;
}

function headquarterManagement(){
$.ajax({
url:"../bin/manage_hq.php",
data:{ 'procAction': 1},
method: 'POST',
dataType: 'JSON',
success: function(proc_msg){

// get data and populate the table using jquery.each() & jquery.append() functions

},
error: function(xhr){
console.log(xhr.responseText);
}
})
return;
}


this code fails to update "tbl_hqlist".

Answer

jQuery load() uses AJAX and is therefore asynchronous, lucky for you, it provides a callback parameter. Adjust like so...

function fn_headquarters(){
    $('#bodyContent').load("../html/headquarters.html", function(){
        headquarterManagement();
    });
    return;
 }

By doing this, you will make sure the element actually exists before populating it.


?Bonus: This will create table markup from json data:

function makeTableFromArray(arrayOfData){
    var html_buffer = [];
    html_buffer.push("<table><thead><tr>");
    var headerData = arrayOfData[0];
    for(var p in headerData)
        if(headerData.hasOwnProperty(p))
            html_buffer.push("<th>"+p+"</th>");
    html_buffer.push("</tr></thead><tbody>");
    for(var i=0; i<arrayOfData.length; i++){
         html_buffer.push("<tr>");
         for(var p in arrayOfData[i])
             if(arrayOfData[i].hasOwnProperty(p))
                 html_buffer.push("<td>"+arrayOfData[i][p]+"</td>");
         html_buffer.push("</tr>");
    }
    html_buffer.push("</table>");
    return html_buffer.join("");
}

https://jsfiddle.net/sbctwdLc/