I get the following JSON String from server as response
[{\"city\":\"AMBALA\",\"cStatus\":\"Y\"},{\"city\":\"ASANKHURD\",\"cStatus\":\"Y\"},{\"city\":\"ASSA
There are many plugins for doing that. I normally use datatables it works great. http://datatables.net/
Try this:
<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table</title>
<style>
th, td, p, input {
font:14px Verdana;
}
tr{
align: right
}
table, th, td
{
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<div id="showData"></div>
</body>
<script>
function CreateTableFromJSON() {
var obj = {[{"city":"AMBALA","cStatus":"Y"},
{"city":"ASANKHURD","cStatus":"Y"},
{"city":"ASSANDH","cStatus":"Y"}]}
var table = document.createElement('table');
var tr = table.insertRow(-1);
function iterate(obj,table,tr){
for(var props in obj){
if(obj.hasOwnProperty(props)){
if(typeof obj[props]=='object')
{
var trNext = table.insertRow(-1);
var tabCellHead = trNext.insertCell(-1);
var tabCell = trNext.insertCell(-1);
var table_in = document.createElement('table');
var tr_in;
var th = document.createElement("th");
th.innerHTML = props;
tabCellHead.appendChild(th);
tabCell.appendChild(table_in)
iterate(obj[props],table_in,tr_in);
}
else
{
if(tr === undefined)
{
tr = table.insertRow(-1);
}
var tabCell = tr.insertCell(-1);
console.log(props+' * '+obj[props]);
tabCell.innerHTML = obj[props];
}
}
}
}
iterate(obj,table,tr);
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>
Try this:
CSS:
.hidden{display:none;}
HTML:
<table id="table" class="hidden">
<tr>
<th>City</th>
<th>Status</th>
</tr>
</table>
JS:
$('#search').click(function() {
$.ajax({
type: 'POST',
url: 'cityResults.htm',
data: $('#cityDetails').serialize(),
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].city && data[i].cStatus){
txt += "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form submission
});