Search code examples
htmljsontabular

How to display my information in table form?


I am using HTML to display my PHP JSON Encoded information but I would like to know how do I display the information in a table? I have already created the PHP which is just a simple array which shows a person's first name, surname and email.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">

    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
    <script src="https://getfirebug.com/firebug-lite-debug.js"></script>

    <title></title>
</head>
<body>

<!-- this UL will be populated with the data from the php array -->
<ul></ul>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<script type='text/javascript'>
    $(document).ready(function(){
        // call the php that has the php array which is json_encoded
        $.getJSON('Test.php', function(data) {
            // data will hold the php array as a javascript object
            console.log(data);
            $.each(data, function(key, val) {
                $('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + '</li>');
            });
        });

    });
</script>

</body>
</html>


Solution

  • <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
    
        <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
    
        <title></title>
    </head>
    <body>
    
    <!-- JSON goes to <tbody> -->
    <table>
    <thead>
    <tr><th>Key</th><th>Name and Email</th></tr>
    </thead>
    <tbody>
    </tbody>
    </table>
    
    <script type='text/javascript'>
        $(document).ready(function(){
            // call the php that has the php array which is json_encoded
            $.getJSON('Test.php', function(data) {
                // data will hold the php array as a javascript object
                $.each(data, function(key, val) {
                    $('tbody').append('<tr><td>' + key + '</td><td>' + val.first_name + ' ' + val.last_name + ' ' + val.email + '</td></tr>');
                });
            });
    
        });
    </script>
    

    You can append the JSON like this.