In my earlier articles, I have already explained how to bind an HTML table in jQuery with AJAX call using different methods. This article will explain how to bind the HTML table using JSON data but with the best method in which you do not require to append the table by specifying the column names. Just call the header function and pass the response in a list as a parameter that converts the list items into the table columns and appends it as a table header to the table using the For loop.
Here is our table structure. In this, we have given different ids to both, the table and the table header. We do this just because our table header is appended in different functions and body is in a different function. Let's see this in details.
- <table id="jsonTable" border="1" style="border-collapse: collapse;" cellpadding="5">
- <thead id="av">
- </thead>
- </table>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
- <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
- $(document).ready(function () {
- tablebind();
- });
Now, using an AJAX call, we can call the web method to bind the table. In my last article, I have already explained all the AJAX calling parameters so you can refer to them. In this procedure, what we do is to call a web method named bind, as given below, and convert the response from the JSON string to JavaScript object using ParseJSON. Then, by passing the data as a parameter, call the Columnheader function which returns the column header and using a Nested For Loop, we append each row in a row$ variable up to the number of records in the data and to the number of columns in a list the For Loop is iterated. After the loop work is done, we need to append the tr$ variable to the table using the id selector.
- function tablebind() {
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "ShipTo.aspx/binds",
- data: "{}",
- dataType: "json",
- success: function (response) {
- var obj = $.parseJSON(response.d);
- if (obj.length > 0) {
- var data = obj[0].Table1;
- var table = $("<table />");
- table[0].border = "1";
- var row$;
- var columns = addAllColumnHeaders(data);
- for (var i = 0; i < data.length; i++) {
- row$ = $('<tr/>');
- for (var colIndex = 0; colIndex < columns.length; colIndex++) {
- var cellValue = data[i][columns[colIndex]];
- if (cellValue == null) { cellValue = ""; }
- row$.append($('<td/>').html(cellValue));
- }
- $("#jsonTable").append(row$);
- }
- }
- },
- error: function (response) {
- //
- }
- });
- }
Our result is already appended to the table above. Now, this function is used to make the table header. This is similar to the above method where we iterated the For Loop to make each <tr>. Now, in this, we need to push each column to the columnset. This method returns the list of the columns to the previous function and appends each <th> to the headertr$ to form the table header.
- function addAllColumnHeaders(myList) {
- var columnSet = [];
- var headerTr$ = $('<tr/>');
- for (var i = 0; i < myList.length; i++) {
- var rowHash = myList[i];
- for (var key in rowHash) {
- if ($.inArray(key, columnSet) == -1) {
- columnSet.push(key);
- headerTr$.append($('<th/>').html(key));
- }
- }
- }
- $("#av").append(headerTr$);
- return columnSet;
- }
There may be a condition that you don't want any column in the HTML table but the query is returning the column. In that case, you can pass the if condition with the column name in the addAllColumnsHeader function. See an example below.
- function addAllColumnHeaders(myList) {
- var columnSet = [];
- var headerTr$ = $('<tr/>');
- for (var i = 0; i < myList.length; i++) {
- var rowHash = myList[i];
- for (var key in rowHash) {
- if ($.inArray(key, columnSet) == -1) {
- if (key != "ShipToId" && key != "GCRETEDON" key != "userid") {
- columnSet.push(key);
- headerTr$.append($('<th/>').html(key));
- }
- }
- }
- }
- $("#av").append(headerTr$);
- return columnSet;
- }
- function addAllColumnHeaders(myList) {
- var columnSet = [];
- if (myList.length > 0) {
- var headerTr$ = $('<tr/>');
- headerTr$.append($('<th/>').html('Action'));
- }
- for (var i = 0; i < myList.length; i++) {
- var rowHash = myList[i];
- for (var key in rowHash) {
- if ($.inArray(key, columnSet) == -1) {
- if (key != "ShipToId" && key != "GCRETEDON" && key != "userid") {
- columnSet.push(key);
- headerTr$.append($('<th/>').html(key));
- }
- }
- }
- }
- $("#av").append(headerTr$);
- return columnSet;
- }
- function tablebind() {
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "ShipTo.aspx/binds",
- data: "",
- dataType: "json",
- success: function (response) {
- var obj = $.parseJSON(response.d);
- if (obj.length > 0) {
- var data = obj[0].Table1;
- var table = $("<table />");
- table[0].border = "1";
- var row$;
- var columns = addAllColumnHeaders(data);
- for (var i = 0; i < data.length; i++) {
- row$ = $('<tr/>');
- row$.append($('<td/>').html('<img src="../images/edit_icon.jpg" id="' + data[i]['ShipToId'] + '" onclick="edt(this)"><img src="../images/Delete1.png" id="' + data[i]['ShipToId'] + '" onclick="dlt(this)"><img src="../images/view.png" id="' + data[i]['ShipToId'] + '" onclick="pop(this)">'));
- for (var colIndex = 0; colIndex < columns.length; colIndex++) {
- var cellValue = data[i][columns[colIndex]];
- if (cellValue == null) { cellValue = ""; }
- row$.append($('<td/>').html(cellValue));
- }
- $("#jsonTable").append(row$);
- }
- sort();
- }
- },
- error: function (response) {
- //
- }
- });
- }
- [System.Web.Services.WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
- public static string binds()
- {
- List<Dictionary<string, Object>> tables = new List<Dictionary<string, object>>();
- //to create tables with table name and their rows.
- List<Dictionary<string, Object>> rows = null;
- //to hold single table with rows
- Dictionary<string, Object> tab = new Dictionary<string, object>();
- // to hold single row of each table.
- Dictionary<string, Object> row = null;
- System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
- SqlConnection con = null;
- con = (SqlConnection)HttpContext.Current.Session["conn"];
- string g3 = "select ShipToId,category_code [Category Code],category_name [Category Name],GCRETEDON,userid,status from category";
- SqlCommand cmdgla = new SqlCommand(g3, con);
- cmdgla.Connection = con;
- SqlDataAdapter adpgla = new SqlDataAdapter(cmdgla);
- DataTable ndt = new DataTable();
- adpgla.Fill(ndt);
- DataTable dtadd = new DataTable();
- DataRow dr1;
- for (int k = 0; k < ndt.Rows.Count; k++)
- {
- dr1 = dtadd.NewRow();
- dtadd.Rows.Add(dr1);
- }
- DataSet ds = new DataSet();
- ds.Tables.Add(ndt);
- foreach (DataTable dt in ds.Tables)
- {
- rows = new List<Dictionary<string, object>>();
- foreach (DataRow dr in ndt.Rows)
- {
- row = new Dictionary<string, object>();
- foreach (DataColumn dc in ndt.Columns)
- {
- row.Add(dc.ColumnName.Trim(), dr[dc]);
- }
- rows.Add(row);
- }
- tab.Add(ndt.TableName.Trim(), rows);
- }
- tables.Add(tab);
- return serializer.Serialize(tables);
- }
Here is the final output with only edit action.
You can see how easy it is for you to bind an HTML table without specifying the table header row and the data rows. This can be a very helpful article for you to start working with JSON data using AJAX call. Also, you can follow the process mentioned above when you are having a bulk data and need to bind the HTML table. According to your requirement, you can edit these functions simply.

amit patelPosted Jul 13, 2020, 12:51 AM
Thanks AC...but why jquery table sorting and searchind not working with this table
Nitin ShakyaPosted Dec 12, 2018, 3:43 PM
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="myform.aspx.cs" Inherits="MyApplicationTest.myform" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script language="javascript"> function deleteRow(btn) { $(btn).closest("tr").remove(); } </script> <script> var aa = new Array(); function add() { var name = $("#name").val(); var Age = $("#age").val(); aa.push(name); var b = aa.length; alert(b); var a=1 var row = ''; row += '<tr id="tr1'+ b+'">'; row += '<td> ' + b + '</td>'; row += '<td> ' + name + '</td>'; row += '<td>' + Age + '</td>'; row += '<td> <input type="button" value="X" id="btnDel4" onclick="deleteRow(this);" /></td>'; row += '</tr>'; a++; alert(row); $("#tbladd").append(row); } </script> </head> <body> <form id="form1" runat="server"> <div> Name: <input type="text" id="name" /> Age:<input type="text" id="age" /> <input type="button" id="btnadd" value="Add" onclick="add() " /> </div> <table border="1" id="tblbind"> <thead> <th>SN.</th> <th>Name</th> <th>Age</th> </thead> <tbody id="tbladd"> </tbody> </table> </form> </body> </html>