I get the following JSON String from server as response
[{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]
Here is my Jquery Code
$('#search').click(function() {
alert("submit handler has fired");
$.ajax({
type: 'POST',
url: 'cityResults.htm',
data: $('#cityDetails').serialize(),
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form submission
});
The alert shows the JSON String Correctly. Now i want to map this response to my table
say
How can i do that ??
Yes, ImportJSON is a really easy tool to use for taking information from JSON and putting it into a table or spreadsheet. Including if you want to parse your JSON directly from Google Sheets!
JSON can very easily be translated into JavaScript. JavaScript can be used to make HTML in your web pages.
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
});
As an alternative to the answers you already have, and for others that come accross this post. I recently had a similar task and created a small jquery plug in to do it for me. Its pretty small under 3KB minified, and has sorting, paging and the ability to show and hide columns.
It should be pretty easy to customize using css. More information can be found here http://mrjsontable.azurewebsites.net/ and the project is available for you to do as you wish with on github https://github.com/MatchingRadar/Mr.JsonTable
To get it to work download the files and pop them in your site. Follow the instructions and you should end up with something like the following:
<div id="citytable"></div>
Then in the ajax success method you will want something like this
success: function(data){
$("#citytable").mrjsontable({
tableClass: "my-table",
pageSize: 10, //you can change the page size here
columns: [
new $.fn.mrjsontablecolumn({
heading: "City",
data: "city"
}),
new $.fn.mrjsontablecolumn({
heading: "City Status",
data: "cStatus"
})
],
data: data
});
}
Hope it helps somebody else!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With