2

So I'm working on an admin panel to help someone at work manage data for a web application I'm building. I'd like to use Handlebars templates to build out different admin panels for different tables in a database. However, I can't even get a test template to work. I've looked at a lot of different tutorials (and I'm using 4.0.5 if that helps at all) but it just won't populate that div. The JSON array and the template both write out to the console when I test it, so the pieces are there. Is there something else I'm missing?

HTML

<?php
  require 'GetJson.php';
?>

<body>
   <div id="nameList"></div>
   <script id="listOutNames" type="text/x-handlebars-template">
      <table class="table">
              {{#each NamesList}}
                      <tr>
                              <td>{{{Name}}}</td>
                      </tr>
              {{/each}}
      </table>
   </script>
   <script src='js/jQuery/jquery-2.2.1.min.js'></script>
   <script src='js/handlebars-v4.0.5.js'></script>
   <script src='js/EditNameList.js'></script>
</body>

JS

var source = $("#listOutNames").html();
var template = Handlebars.compile(source);
var data = <?php echo json_encode(array('NameList'=>$NamesList)) ?>;
$("#nameList").append(template(data));

PHP

<?php
require 'auth.php';

$link = mysqli_connect($hostname,$username,$password,$database,3306);

$query = "select Name from Names order by NameID";

$result = mysqli_query($link, $query) or die(Mysqli_error($link));

$NamesList = array();

while($row = mysqli_fetch_array($result)){
    $NamesList[] = array('Name' => $row['Name']);
}

mysqli_close($link);

?>

The PHP script produces:

{"NamesList":[{"Name:":"Alice"},{"Name":"Bob"},{"Name":"Clark"}]}

1 Answers1

0

Here is your example working, https://jsfiddle.net/yfr7v7so/

You must import jQuery for your example works in this line:

$("#listOutNames").html()

and trying wrapping your echo with JSON.Parse, like this:

var data = JSON.parse(<?php echo json_encode(array('NameList'=>$NamesList)) ?>);
Jose Rojas
  • 3,490
  • 3
  • 26
  • 40
  • I forgot to add the calls to JQuery, the PHP script, and Handlebars in the original question, but they're there in my project. I've been playing with it, and I think the problem lies in Handlebars not being able to read the JSON object I pass to it. – Quinncuatro May 02 '16 at 16:32