Sowmith Reddy N
Sowmith Reddy N

Reputation: 25

populate json data into html table using ajax call

i am trying to populate json data produced by rest web services into html table. this is my html code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>
</head>
<body>
    <h1>Employee List</h1>
    <form>
        <table  id= "content">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Age</th>
                <th>Salary</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody id = "emp">
        </tbody>    
        </table>
    </form>
    <script>

    $(document).ready(function(){
        alert("1");
        var data = $("#employee").val();
        alert("2");
        $.ajax({

            url: '/rest/restemployees',
            type: 'GET',
            dataType: 'JSON',
            success: function(data){
                alert("3");
                $.each(data, function(i,value){
                    $("#content tbody").append("<tr>" + "<td>" + value.id + "</td>" +
                            "<td>" + value.name + "</td>" +
                            "<td>" + value.age + "</td>" +
                            "<td>" + value.salary + "</td>" +
                            "<td>" + value.address + "</td>" + "</tr>")
                });

            },
            error: function(data){
                alert("4");
            }

        });
    });

    </script>
</body>
</html>

please help me

note: alerts are used just to know the flow

Content is the table id. i don't know where the mistake is. can anyone help me to solve this

Upvotes: 1

Views: 1633

Answers (1)

RAHUL S R
RAHUL S R

Reputation: 1579

I would do something like

success: function(data){
                alert("3");
              $(data).each(function(){ 
                    $('#tbody').append('<tr><td>' + this.id + '</td><td>' + this.name + '</td><td>' + this.age + '</td><td>' + this.salary + '</td><td>' + this.address + '</td></tr>')
                });

and instead of giving table id just put an id to table body where you want to append

Upvotes: 1

Related Questions