Set JSON values to HTML Table in Java Script? - javascript

function loadUserTable(userType){
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
alert(response);
},
});
}
Im still working on it,
I print alert for output and got as below
[{
"userId":1,
"email":"santosh.jadi95#gmail.com",
"mobile":"9900082195",
"gender":"male",
"qualification":"1",
"dob":"2016-01-01",
"login":{
"loginId":1,
"userName":"santosh",
"password":"santosh",
"userType":"admin"
}
}]
I want the above JSON values in an HTML Table, is it Possible?
If yes, then i just want to know that, how it can be done?

Got the Solution,, Thank u all for the kind support
function loadUserTable(userType){
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
var obj = JSON.parse(response);
$("#tableId").html("");
var tr+="<tr><th>User ID</th><th>User Name</th></tr>";
for (var i = 0; i < obj.length; i++){
tr+="<tr>";
tr+="<td>" + obj[i].userId + "</td>";
tr+="<td>" + obj[i].login.userName + "</td>";
tr+="</tr>";
}
$("#tableId").append(tr);
}
});
}

Yes it is possible. if you want to print json data in simple html table then just iterate (use loop) till your json length and construct your table inside loop.
But i will suggest you to use dataTable / bootstrap table plugin there you just need to pass json at the initialization time.
for Example,
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').append(tr);
}
});
});

You'd simple just create a for loop inside success as following:
the obj[i] down below is just a placeholder. You'd have to get the correct value you want to place there.
HTML table container:
<div id="tableContainer">
<table>
<tbody class="tableBody">
<tbody>
</table>
</div>
JSON to append to table:
function loadUserTable(userType)
{
var TableHTML = '';
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
alert("eeee: "+response);
var obj = JSON.parse(response);
for (i = 0; i < obj.length; i++)
{
TableHTML += '<tr><td>' + obj[i].userId + '</td></tr>';
}
},
});
$(".tableBody").append(TableHTML);
}

Related

Clear table before reloding the data in a table

I am trying to bind data from the database. what is happening is that it binds every 5 seconds. Now its binding properly but it does not clear the earlier data. it keeps pilling up. So if there is 3 rows .. it needs to show only 3 rows. now what is happening is it is adding 3 rows every 5 seconds and keeps pilling 6-9-12 every 5 seconds.
I need to clear the data and then load every 5 seconds.
<script type="text/javascript">
$(document).ready(function () {
Get();
setInterval(function () {
Get() // this will run after every 5 seconds
}, 5000);
});
function Get() {
$.ajax({
type: "POST",
url: "../adminpage/noti.ashx",
data: {},
dataType: "json",
success: function (response) {
$.each(response, function (index, itemData) {
var tr = "<tr>" +
"<td>" + itemData.msg + "</td>" +
"<td>" + itemData.dt + "</td>" +
"</tr>";
$("#testTable").find("tbody").append(tr);
});
BindTable();
}
});
}
function BindTable() {
try {
$('#testTable thead th').each(function (i) {
var title = $('#testTable thead th').eq($(this).index()).text();
if (title != "") {
$(this).html('<div style="width:40%;text-align:center;white-space:nowrap">' + title + '</div>');
}
});
}
catch (e) { }
}
</script>
<table id="testTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="m-list-timeline__text" style="width:70%">msg</th>
<th class="m-list-timeline__time" style="width:30%">dt</th>
</tr>
</thead>
<tbody></tbody>
</table>
Try clearing all <tr>nodes from your tbody before you append your results:
success: function (response) {
$("#testTable").find("tbody").empty(); //clear all the content from tbody here.
$.each(response, function (index, itemData) {
/*do stuff*/
$("#testTable").find("tbody").append(tr);
});
BindTable();
}
$('#myTable').empty()
try to remove the content of the table before the ajax call
then fill the data
<script type="text/javascript">
$(document).ready(function () {
Get();
setInterval(function () {
Get() // this will run after every 5 seconds
}, 5000);
});
function Get() {
$.ajax({
type: "POST",
url: "../adminpage/noti.ashx",
data: {},
dataType: "json",
success: function (response) {
// Check if response data is not empty
if (response) {
// Empty previous data
$("#testTable").empty();
// Iterate data for each row
$.each(response, function (index, itemData) {
var tr = "<tr>" +
"<td>" + itemData.msg + "</td>" +
"<td>" + itemData.dt + "</td>" +
"</tr>";
$("#testTable").find("tbody").append(tr);
});
BindTable();
}
}
});
}

Jquery ajax call inside another ajax call is not working as expected inside a for loop

I have an ajax call within a for loop which is inside another ajax call. The code is as follows:
$.ajax({
type: "GET",
url: URI, //URI
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Json) {
var tr = '';
tr = tr + '<tr>';
for (var i = 0; i < Json.length; i++) {
debugger;
tr = tr + '<td>'
tr = tr + '<table><tr><td>'
tr = tr + '<div id="theDiv" class="DivClass">';
tr = tr + '<img id="btnEdit" onclick="EditLevelZeroValue(' + Json[i].ID + ')" src="../Images/Edit-icon.png" title="Edit" alt="Smiley face" style="padding-left:24px;"><img src="../Images/delete.gif" title="Delete" alt="Smiley face" style="margin-left:-17px;margin-bottom:-70px;">';
tr = tr + " <label id='LevelLbl' style='position:relative; z-index:2;top: 20px; color:white;'> " + Json[i].Title + " </label>";
tr = tr + " </div> ";
tr = tr + " </td> ";
tr = tr + "</tr> ";
var URI1 = OMSiteUrl + 'api/Levels/GetLevelOne?subModuleID=' + 1 + '&parentId=' + Json[i].ID;
debugger;
$.ajax({
type: "GET",
url: URI1, //URI
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Json1) {
debugger;
for (var j = 0; j < Json1.length; j++) {
debugger;
if (Json1[j].Publish==true)
{
tr = tr + "<tr><td>";
tr = tr + '<div id="theDiv" Class="DivClass2">';
tr = tr + '<img src="../Images/Edit-icon.png" title="Edit" alt="Smiley face" style="padding-left:6px;margin-top:-40px;"><img src="../Images/delete.gif" title="Delete" alt="Smiley face" style="margin-left:-17px;margin-bottom:-35px;">';
tr = tr + " <label id='LevelLbl' class='font'style='margin-top:17%;margin-left:26%'> " + Json1[j].Title + "</label>";
tr = tr + "</td></tr>"
}
else
{
tr = tr + "<tr><td>";
tr = tr + '<div id="theDiv" Class="DivClassChange">';
tr = tr + '<img src="../Images/Edit-icon.png" title="Edit" alt="Smiley face" style="padding-left:6px;margin-top:-40px;"><img src="../Images/delete.gif" title="Delete" alt="Smiley face" style="margin-left:-17px;margin-bottom:-35px;">';
tr = tr + " <label id='LevelLbl' class='font'style='margin-top:17%;margin-left:26%'> " + Json1[j].Title + "</label>";
tr = tr + "</td></tr>"
}
}
},
error: function () { alert('error'); }
});
tr = tr + "</table>";
tr = tr + "</td>";
}
tr = tr + '</tr>';
$('#levelBox').html(tr);
//tr = tr + '</tr>';
//$('#levelBox').html(tr);
},
error: function () { alert('error'); }
});
I have a for loop inside first ajax call and inside that for loop i have ajax call for each iteration. I want the code to execute the following way:
First ajax call returns list of data, for each data I need to create a table and fetch another list of data and bind to the same table and for second iteration i need to create another table and fetch another list of data and bind it to the newly created table.
EXPECTED RESULT
Now whats happening is, first ajax call returns a list of data and for each data, tables are created. Later the other list of data is fetched and it binds it to one table alone.
If i make async as false, the result is as follows:
Async False results
Can someone help me?
You should use a closure
for (var i = 0; i < arr.length; i++) {
(function(i) {
// your stuff
})(i);
}
or $.each() which creates a closure for you
So in your case
for (var i = 0; i < Json.length; i++) {
(function(i) {
// your stuff
})(i);
}
Use async: false in the ajax call
$.ajax({
type: "GET",
url: URI1, //URI
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Json1) {
... // your code
}
});
The 'A' in AJAX stands for 'asynchronous' which means your looped AJAX calls will be fired sequentially. If you need to wait on your 'success' callback to complete before triggering the next request, you can set the 'async' option to false.
$.ajax({
async: false,
// ...
});

Display JSON result in Table Format

$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
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].die_no && data[i].status && data[i].location) {
txt += "<tr><td>"+data[i].die_no+"</td><td>"+data[i].status+"</td><td>"+data[i].location+"</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
Controller page
$die_no = array();
$status = array();
$location = array();
while ($row = mysql_fetch_array($query)) {
$die_no[] = $row["die_no"]; // or smth like $row["video_title"] for title
$status[] = $row["status"];
$location[] = $row["location"];
}
$res = array($die_no, $status, $location);
echo json_encode($res);
HTML page
<p>
<table id="table" class="hidden">
<tr>
<th>die_no</th>
<th>Status</th>
<th>Location</th>
</tr>
I would like to display result in HTML table format, so I have passed my result in array format to Json but the results are not displayed in HTML page.
I could see the response by using chrome Inspect element under network option . Please help me to display the retrieved results in HTML tabular format.
If you add console.log(data) in your succes response,you can see how the object is structured.
To access the desired json value you should try data['die_no'][i],data['status'][i],data['location'][i].
You can insert the response like this:
<table id="tbl">
</table>
Javascript:
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
if (len > 0) {
for (var i = 0; i < len; i++) {
$('$tbl').append("<tr><td>"+data['die_no'][i]+"</td><td>"+data['status'][i]+"</td><td>"+data['location'][i]+"</td></tr>");
}
}
}
}
}); //you missed this in your question
Use this
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
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[0][i] || data[1][i] || data[2][i]) {
txt += "<tr><td>" + data[0][i] + "</td><td>" + data[1][i] + "</td><td>" + data[2][i] + "</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
});
Actually your php code is not returning key value pair. So in your js you cannot use data.die_no etc
Use this like just I did:
data[0][i]
You have syntax error:
use
txt += <tr><td>
instead of
txt += tr><td>
after if condition

Adding JSON data to table in AJAX

Ok i have some search results from input box. I used keyup to get results. Then tis results send to AJAX, and i want to append it to table. My problem is because i use append i will get more than one table headers if i have more results, on the other side i cant use html() because script use for loop so i will only get one result. Can someone help me to solve this problem. I try something like this...
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);;
$('#result').html('');
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
$('#result').append('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody><tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr> </tbody></table> ' );//dodavanje rezultata u div
}
}
})
}
});
Just create the table once and then append trs in the loop to its tbody
$('#warning').html(response.msg);
if (response.result.length) {
var $table = $('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody></tbody></table>').appendTo($('#result').html(''));
var $tbody = $table.find('tbody');
for (var i = 0; i < response.result.length; i++) //petlja za pristup json
{
$tbody.append('<tr><td>' + response.result[i].id + '</td><td>' + response.result[i].naslov + '</td><td>' + response.result[i].autor + '</td><td>' + response.result[i].cena + '</td><td>' + response.result[i].valuta + '</td></tr> '); //dodavanje rezultata u div
}
} else {
$('#result').html('')
}
Try this :
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);
// Store jQuery objects if used more than once
var $table = $('<table class="page-list">').appendTo($('#result')),
$thead = $('<thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead>').appendTo($table),
$tbody = $('<tbody>').appendTo($table);
innerHTML = '';
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
innerHTML += '<tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr>' );//dodavanje rezultata u div
}
// Append to HTML only once, when you have the full HTML to append
$tbody.append(innerHTML);
}
})
}
});

Pulling in JSON via AJAX to populate a Drop-Down

I am pulling in some JSON data that will vary... for instance:
Data returned could be:
[{"userID":"2779","UserFullName":" Absolute Pro-Formance"},{"userID":"2780","UserFullName":" AR Fabrication"},{"userID":"2781","UserFullName":" Banda Lucas Design Group"}]
or:
[{"orderID":"112958","OrderName":"Order ID: 112958"},{"orderID":"112957","OrderName":"Order ID: 112957"},{"orderID":"112956","OrderName":"Order ID: 112956"}]
What I am attempting to do is process this JSON to build a <select> list.
// Load in a drop-down as JSON
function LoadDropDown($url, $where, $id, $selectName){
var $loading = '<div class="pageLoader" style="margin:0 auto !important;padding:0 !important;"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>';
var $t = Math.round(new Date().getTime() / 1000);
var $container = jQuery($where);
var options = {
url: $url + '?_=' + $t,
cache: false,
type: 'POST',
beforeSend: function(){
$container.html($loading);
},
success: function(data, status, jqXhr){
$html = '<select class="form-control" id="'+$selectName+'" name="'+$selectName+'">';
$html += '<option value="0">- Select an Option -</option>';
for(var i = 0; i < data.length-1; ++i) {
var item = data[i];
console.log(item.userID);
}
$html += '</select>';
$container.html('<pre>' + data + '</pre>');
},
complete: function(jqXhr, status){},
error: function(jqXhr, status, error){
$container.slideDown('fast').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><i class="fa fa-exclamation-triangle fa-4x pull-left"></i><p><strong>Danger Will Robinson!</strong><br />There was an issue pulling in this page. Our support team has been notified, please check back later.</p></div>');
}
};
jQuery.ajax(options);
}
The issue I am having is... #1 console.log(item.userID); always shows undefined, and #2 how can I effecitvely dynamically build the options? The returned JSON will ALWAYS contain 2 items per row and id, and a name
UPDATE
for(var $key in data){
var $val = data[$key];
for($j in $val){
console.log('name:' + $j + ' = ' + $val[$j]);
}
}
Is showing me what I need in Firefox Console... But 1 item per line, for each (for example the 1st JSON) name:userID = 1234 next line name:UserFullName = TheName
How can I get them so I can build my <options>?
With:
for(var k in data) {
console.log(k, data[k]);
}
I am returned:
2955 Object { orderID="8508", OrderName="Order ID: 8508"}
and
2955 Object { userID="1355", UserFulleName="Me Myself And I"}
You don't need to use such messy code. Also in your Ajax setup dataType:"json"
success:function() {
var listB=$('#yourdropdownId');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option>', {
value: item.userID,
text: item.UserFullName
}, '<option/>'))
});
}
Also the $.getJson instead of ajax if you only want retrieve json from server
$.getJSON('#Url.Action(" "," ")',
{ "youparametername": yourdata}, function (data) {
$.each(data, function (index, item) {
})
});
inside the options object, make sure to use the
dataType: 'json'
Or in the success handler you can use
JSON.parse(data)
Cured: Changed my loop to cycle through each item in the returned JSON, got their keys, etc...
var $dl = data.length;
for(var $i = 0; $i < $dl - 1; ++$i) {
var $keys = Object.keys(data[$i]);
$html += '<option value="' + data[$i][$keys[0]] + '">' + data[$i][$keys[1]] + '</option>';
}

Categories

Resources