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>
After the table structure, add the bootstrap and jQuery files. Then, let us call the tablebind function in the document so as to bind the table at the time of page load.
- <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;
- }
Similarly, you might want to add an extra column to the HTML table, like edit and delete. For this, you have to change both the functions. Let's look at the changes in addAllColumnsHeader function first.
- 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;
- }
Now, let's see the bind function's code.
- 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) {
-
- }
- });
-
- }
In the above function, we added the row with two icons - edit and delete - which call their respective functions. Here, I am not explaining the edit and delete functions for those are explained in
my earlier article. Now, our last step would be the web method that we call from our AJAX method.
- [System.Web.Services.WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
- public static string binds()
- {
- List<Dictionary<string, Object>> tables = new List<Dictionary<string, object>>();
-
- List<Dictionary<string, Object>> rows = null;
-
- Dictionary<string, Object> tab = new Dictionary<string, object>();
-
- 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.