JamesG
JamesG

Reputation: 2018

Creating a dynamic table from AJAX reply query

I have the following code:

            var htmlname='';
            var names = result.names
            $.each(names, function( i, name){

               htmlname = "<td>" + name + "</td>";

               $('#adminall tr:last').html(htmlname);

                var row = document.createElement('tr');
                var tableCurrentPoints = document.getElementById("adminall"); // find table to append to
                tableCurrentPoints.appendChild(row); // append row to table


            });


            var htmlemail='';
            var emails = result.emails
            $.each(emails, function( ii, email){

               htmlemail = "<td>" + email + "</td>";

               $('#adminall tr:last').html(htmlemail);

                var row = document.createElement('tr');
                var tableCurrentPoints = document.getElementById("adminall"); // find table to append to
                tableCurrentPoints.appendChild(row); // append row to table


            });

And then the table which its appending too:

        <table id="adminall" style="margin:10px 0px 0px 0px;" width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr id="adminallheader">

        </tr>
        <tr></tr>

    </table>

This is from a success handler within an AJAX request. I am attempting to create a table populated with the data from the query, and I'm guessing it should be created in Javascript as I am attempting here, but I can't get it to work. At the moment it has all the data (name and email) in one column, but it needs to be split across the two.

Any ideas?

Upvotes: 0

Views: 2600

Answers (1)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You should do something like

       var names = result.names
       $.each(names, function( i, name){
           //get the corrsponding email
           var email = result.emails[i];
           var htmlname = "<td>" + name + "</td><td>"+email"</td>";

           $('#adminall tr:last').append(htmlname);

            var row = document.createElement('tr');
            var tableCurrentPoints = document.getElementById("adminall"); // find table to append to
            tableCurrentPoints.appendChild(row); // append row to table


        });

and loop only once and not twice.

Upvotes: 2

Related Questions