Search code examples
javascripthtmldomappendchild

appendChild wont work?


I'm trying to make an inbox that will show messages when you first load the page or click a button, but nothing is showing up. What did I do wrong?

var inbox = document.getElementsByClassName("inbox").item(0);
var inbox_button = document.getElementById("messages");
inbox_button.addEventListener("click", showMessages);
showMessages();

function showMessages() {
  var messages = "<?php echo $inbox ?>";
  var inbox_table = document.createElement("table");
  var inbox_content =
    "<tr>" +
    "<th>From</th>" +
    "<th>Subject</th>" +
    "<th>Date</th>" +
    "</tr>";
  for (i = 0; i < messages.length; i++) {
    inbox_content = inbox_content +
      "<tr>" +
      "<td>" + messages[i][1] + "</td>" +
      "<td>" + messages[i][2] + "</td>" +
      "<td>" + messages[i][5] + "</td>" +
      "</tr>";
  }
  inbox_table.innerHTML = inbox_content;
  inbox.appendChild(inbox_table);
}
<div class="inbox">
  <button id="messages" type="button">Inbox</button>
  <button id="new_message" type="button">New Message</button>
</div>


Solution

  • You are populating messages as a String var messages = "<?php echo $inbox ?>";, between quotes, and your logic expects a 2 dimensional array, so the variable $inbox should return text as a Javascript's array of arrays, for instance:

    PHP:

    $inbox = '[["Text-1-1", "Text-1-2", "Text-1-3"], ["Text-2-1", "Text-2-2", "Text-2-3"]]';
    

    Javascript (straight, no quotes):

    var messages = <?php echo $inbox ?>;