locked
how to create dynamic table with ajax RRS feed

  • Question

  • User-1634604574 posted

    i wrote this code but is not working 

    var table = $('<table border="0" style="width:200px"></table>');

    var HTML = "<table class='table table-striped table-bordered table-hover' style='width:500px'>";

    HTML += "<tr><th>Description</th></tr>";
    for (var i = 0; i < jsonArr11.length; i++) {

    if (i == 0) {
    first= jsonArr11[i].col1
    }

    if (jsonArr11[i].col1 == first) {

    // row += '<tr><td>sss</td></tr>'
    //row += '<tr>'
    // + '<td>' + jsonArr11[i].col2 + '</td></tr>'

    HTML += "<tr><td>" + jsonArr11[i].col2 + "</td></tr>";

    }


    if (jsonArr11[i].col1 != first) {

    first = jsonArr11[i].col1


    }
    }
    HTML += "</table>";

    Tuesday, January 22, 2019 4:51 AM

Answers

  • User839733648 posted

    Hi zhyanadil.it@gmail.com,

    According to your description and code, I've made a sample on my side.

    I've just simulated the response jsondata.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
        <script>
            $(function () {
                var jsonData = '[{"id":"1","name":"Helen","age":"23"},{"id":"2","name":"Bob","age":"25"},{ "id":"3", "name":"Timmy", "age":"26"}]';
                response = $.parseJSON(jsonData);
                var table = '<table id="mytable" class="table table - striped table - bordered table - hover" style="width: 500px"><tr><th>ID</th><th>Name</th><th>Age</th></tr ></table>';
                $('body').append(table);
                var trHTML = '';
                $.each(response, function (i, item) {
                    trHTML += '<tr><td>' + item.id + '</td><td>' + item.name + '</td><td>' + item.age + '</td></tr>';
                });
                $('#mytable').append(trHTML);
            })
    
        </script>
    </head>
    <body>
    </body>
    </html>

    result:

    If you want to use ajax, you could write like below.

    $.ajax({
        url: '/',
        type: 'POST',
        data: {
            json: jsonData
        },
        success: function (response) {
            var trHTML = '';
            $.each(response, function (i, item) {
                trHTML += '<tr><td>' + item.id + '</td><td>' + item.name + '</td><td>' + item.age + '</td></tr>';
            });
            $('#mytable').append(trHTML);
        }
    });

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 23, 2019 7:15 AM