0

I am trying to dynamically create an HTML table with data from a MySQL table. The data in the table is not static and as such the HTML table needs to be updated when the database table is.

Here is my PHP code:

 $sql = "SELECT * FROM pendingusers";
$result = $conn->query($sql);
$response = array(); //$result->fetch_all(MYSQLI_ASSOC);

if ($result->num_rows > 0) {
    $i = 1;
    while($row = $result->fetch_assoc()) //$response[] = $row; 

{    

    $response[$i]['fname'] = $row["firstname"];
    $response[$i]['lname'] = $row["lastname"];
    $response[$i]['uname'] = $row["username"];
    $response[$i]['email'] = $row["email"];
    $response[$i]['password'] = $row["password"];
    $i++;
}

 echo json_encode($response);   

} else {
    echo "0 results";
}
$conn->close();

?>

Here is my Javascript function to call the PHP file:

function load() {   

            // var users = null;    
            $.post(
            "Returnsmedb.php",
            function (response) {
               console.log(response);
            }, 'json'
        );           
}

This returns an object, with three interior objects, each representing a row, like so : Object { 1: Object, 2: Object, 3: Object }. Each interior object has the fields email, fname, lname, password, uname.

I'm not sure where to go from here. I think this needs to converted to a JavaScript array but I have not found great examples. What do I need to do to get this data into a table?

Each row of the table should correspond to one of the interior objects with appropriate field headings. Also, each row needs to have two buttons that will delete it from the table or add the values to another database table.

halfer
  • 19,824
  • 17
  • 99
  • 186
Evan Lalo
  • 1,209
  • 1
  • 14
  • 34
  • Are you after pure JS or are you using a library, like JQuery, ExtJS, React, etc.? – Meezaan-ud-Din Jul 26 '17 at 15:38
  • @Meezaan-ud-Din `$.post` is jQuery – Patrick Barr Jul 26 '17 at 15:39
  • This may be of use to you: [Dynamic creation of table with DOM](https://stackoverflow.com/questions/8302166/dynamic-creation-of-table-with-dom) – nageeb Jul 26 '17 at 15:39
  • Oops, sorry, I only read the first pat - didn't even see the second with the $.post. – Meezaan-ud-Din Jul 26 '17 at 15:53
  • @nageep I have tried to create a table in a similar fashion, but every time I reference the returned data (response) it says that it is not defined. Any ideas? – Evan Lalo Jul 26 '17 at 15:54
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Jul 26 '17 at 21:10

2 Answers2

1

Here's one of the ways you can use jQuery to construct HTML markup based on your data.

var data = [
{
  email: "abc@def.ghi", 
  fname: "abc", 
  lname: "def", 
  password: "abcDef",
  uname: "defAbc"
},{
  email: "1abc@def.ghi", 
  fname: "2abc", 
  lname: "3def", 
  password: "4abcDef",
  uname: "5defAbc"
},{
  email: "6abc@def.ghi", 
  fname: "7abc", 
  lname: "8def", 
  password: "9abcDef",
  uname: "0defAbc"
}
];

var tableBody = "";

var columns = [];

// Create the header record.
tableBody = tableBody + "<tr>";
for(var prop in data[0]) {
  if(data[0].hasOwnProperty(prop)) {
    // Append properties such as email, fname, lname etc.
    tableBody = tableBody + ("<th>" + prop + "</th>");
    
    // Also keep a list of columns, that can be used later to get column values from the 'data' object.
    columns.push(prop);
  }
}

tableBody = tableBody + "</tr>";

// Create the data rows.
data.forEach(function(row) {
  // Create a new row in the table for every element in the data array.
  tableBody = tableBody + "<tr>";

  columns.forEach(function(cell) {
    // Cell is the property name of every column.
    // row[cell] gives us the value of that cell.
    tableBody = tableBody + "<td>" + row[cell] + "</td>";
  });
  
  tableBody = tableBody + "</tr>";
});

$("#usersTable").append(tableBody);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="usersTable">

</table>
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • This seems like something that could work. I am a little confused about how I actually get my data from my MYSQL table into it. Each time I try to reference my "response" object outside of my load function, I get an undefined error. I realize that "response" is a local object to the function, so I am not sure how to get past that. – Evan Lalo Jul 26 '17 at 16:46
  • That's a very broad question, but here are some general steps that you should learn: 1. Convert the data array from PHP to JSON. Once you have JSON object, you could easily pass that into Javascript. 2. Since you wish to add/delete individual records on the table using Javascript, you might need to create an AJAX endpoint in PHP that you could access using JQuery. 3. Once done, you can create buttons in the HTML markup of the page that call JQuery functions to call your PHP through AJAX. – Nisarg Shah Jul 26 '17 at 17:00
0

Here is how I got it to work.

function load() {   


            $.post(
            "Returnsmedb.php",
            function (response) {

                var block = []

                index = 0;
                for (var item in response){

                    var objectItem = response[item];

                  var firstname = objectItem.fname;
                  var lastname = objectItem.lname;
                  var username = objectItem.uname;
                  var email = objectItem.email;
                  var password = objectItem.password;
                  var deny = document.createElement("input");
                  deny.type = "checkbox";
                  deny.className = "chk";
                  deny.name = "deny";
                  deny.id = "deny";
                  var approve = document.createElement("input");
                  approve.type = "checkbox";
                  approve.className = "chk";
                  approve.name = "approve";
                  var moreinfo = document.createElement("input");
                  moreinfo.type = "checkbox";
                  moreinfo.className = "chk";
                  moreinfo.name = "moreinfo";

                    block.push(firstname);
                    block.push(lastname);
                    block.push(username);
                    block.push(email);
                    block.push(password);
                    block.push(deny);
                    block.push(approve);
                    block.push(moreinfo);

                    dataset.push(block);
                    block = [];


                }




                 var data = [" First Name", " Last Name "," User Name ", " Email ", "Password", " Deny", "Approve", "More Information"]

                tablearea = document.getElementById('usersTable');
                table = document.createElement('table');
                thead = document.createElement('thead');
                tr = document.createElement('tr');

                for (var i = 0; i < data.length; i++) {
                    var headerTxt = document.createTextNode(data[i]);
                    th = document.createElement('th');
                    th.appendChild(headerTxt);
                    tr.appendChild(th);
                    thead.appendChild(tr);
                }

                table.appendChild(thead);


                for (var i = 0; i < dataset.length; i++) {
                    tr = document.createElement('tr');
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td'));
                    tr.appendChild(document.createElement('td')); //Added for checkbox
                    tr.appendChild(document.createElement('td')); //Added for checkbox
                    tr.appendChild(document.createElement('td')); //Added for checkbox


                    tr.cells[0].appendChild(document.createTextNode(dataset[i][0]));
                    tr.cells[1].appendChild(document.createTextNode(dataset[i][1]));
                    tr.cells[2].appendChild( document.createTextNode(dataset[i][2]));
                    tr.cells[3].appendChild( document.createTextNode(dataset[i][3]));
                    tr.cells[4].appendChild( document.createTextNode(dataset[i][4]));
                    tr.cells[5].appendChild((dataset[i][5])); //
                    tr.cells[6].appendChild((dataset[i][6])); //
                    tr.cells[7].appendChild((dataset[i][7])); //
                    table.appendChild(tr);                   
                }
                tablearea.appendChild(table);


                $('input.chk').on('change', function() {
                if($('this:checked'))
                {
                    var tr =$(this).parents('tr');
                tr.find("input.chk").not(this).each(function(){
                $(this).prop('checked', false);
                });
                }

                });
            }, 'json'
        );           
}
Evan Lalo
  • 1,209
  • 1
  • 14
  • 34