user_78361084
user_78361084

Reputation: 3908

How do I create a table dynamically upon getting a successful ajax response?

I'm returning data from our database and creating a table dynamically. If the call to page1.php is successful, we create a table with one header row and then loop through the results and make some rows. How do I add a single header row? thx!

$.post("page1.php", {user: "homer"}, 
function(data){
// output the header row
  function(test){
  var tblHdr ='<th>'+'Username'+'</th>';
  $(tblHdr).appendTo("#tble");
  };

// output the user data
   $.each(data.userdata, 
     function(i,details){

     var tblRow ='<tr>'+'<td>'details.name+'</td>'+'</tr>';
         $(tblRow).appendTo("#tble");

    });
   }, "json"
);

Upvotes: 0

Views: 414

Answers (1)

Kai Qing
Kai Qing

Reputation: 18833

why do you even need or want that function in there? If you remove the whole function declaration from that block and just append the th as defined then you should be fine. assuming tblHdr and tblRow are defined somewhere.

$.post("page1.php", {user: "homer"}, 
function(data){
// output the header row

  var tblHdr ='<th>'+'Username'+'</th>';
  $(tblHdr).appendTo("#tble");


// output the user data
   $.each(data.userdata, 
     function(i,details){

     var tblRow ='<tr>'+'<td>'details.name+'</td>'+'</tr>';
         $(tblRow).appendTo("#tble");

    });
   }, "json"
);

Upvotes: 1

Related Questions