Populate table with jquery/json - javascript

I have an asp.net web page and I want to populate the table with jquery, ajax web service call something. But I am not strong on it at all.
The html part for the table is:
<tbody id="testBody">
<tr id="templateEquipment" class="hidden">
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td class="hidden">
</td>
</tr>
</tbody>
I already defined the columns and the table is empty at the beginning. And in jquery
function SearchEquipment() {
$.ajax({
type: "POST",
url: pageName + "SearchEquipment",
data: "{'oParams':" + JSON.stringify(BeginSearch()) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d.length > 0) {
$.each(response.d, function (i, item) {
<!-- add row to fill the table-->
Thanks for your help. I do not have the resources for that(links are welcomed).

You can do it like this.
var html = $.map(response.d, function (item, i) {
return "<tr><td>" + item.value1 + "</td><td>" + item.value2 + "</td></tr>";
}).join("");
$("#testbody").append(html);
By creating a big string with all the rows and cells in it you only need to add it once to the DOM which is a lot quicker!

Related

How to reload view after AJAX POST

Being new to AJAX I have encountered this problem and have had no luck resolving it. I want my table to be refreshed after an ajax post to review an object, everything I've tried has been futile.
Assume the ajax response is a JSON result, to avoid posting my OnPost() code.
I send the Id of the product using ajax and then use that Id to remove the product
I then call the same method OnGet() uses to populate the tables which returns the updated list. In chrome debug tools I see the response successfully returns with the updated list. I just don't know how to get it across back to my list. Thanks in advance guys.
#Html.AntiForgeryToken()
<table id="shoppingBag" class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.ShoppingBagItems)
{
<tr>
<td>
#item.Product.Name
</td>
<td>
#item.Price.ToString("C")
</td>
<td>
<input value="#item.Quantity" size="1" maxlength="1" class="text-center" />
</td>
<td>
<button onclick="remove(#item.Product.Id.ToString())" class="close">
<span aria-hidden="true">×</span>
</button>
</td>
</tr>
}
</tbody>
</table>
<script>
function remove(id) {
$.ajax({
type: 'POST',
url: 'ShoppingBag?handler=Delete',
headers: {
"XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: ''+id+'',
sucess: function (response) {
append_json(response);
}
});
}
function append_json(data){
var table = document.getElementById('shoppingBag');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.product.name +
'</td>' +
'<td>' +
object.price +
'</td>' +
'<td>' +
object.quantity +
'</td>';
table.appendChild(tr);
});
}
</script>
In Ajax success method after this append_json(response);add below code to refresh the table
$("#shoppingBag").load(window.location + " #shoppingBag");
change:
var table = document.getElementById('shoppingBag');
to:
var table = $('#shoppingBag tbody');
AND
change:
table.appendChild(tr);
to:
table.append(tr);
you are appending your data to main <table> if you inspect your table you can see the appended html.but you need to append data in body of table
for this you can use $("#shoppingBag tbody").append(tr);
or you can add id to <body> like <tbody id="myTestTableBody"> and use this in to your JavaScript
function append_json(data){
var table = document.getElementById('myTestTableBody');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.product.name +
'</td>' +
'<td>' +
object.price +
'</td>' +
'<td>' +
object.quantity +
'</td>';
table.appendChild(tr);
});
}
I have added a sample code that how you can append data to existing table
var page=1;
function AddData() {
$.ajax({
url: "https://reqres.in/api/users?page="+page,
type: "GET",
success: function(response){
append_json(response.data);
}
});
page++;
}
function append_json(data){
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.first_name +
'</td>' +
'<td>' +
object.last_name +
'</td>' +
'<td>' +
'<img src ='+object.avatar +' width="50px" height="50px" />'+
'</td>';
$("#shoppingBag tbody").append(tr);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Add Data" onclick="AddData()">
<table id="shoppingBag" class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

var query not returning required results

I have a javascript file which is returning results to a HTML page via information entered in a SharePoint list. It works fine, but I've been asked to return another field of multiple text called 'Further Details'. However it's not showing up on the HTML page. I've checked the console and the information being entered in the Further Details field is being returned, it's just not showing on the HTML page. The rest (Current Status, Typical Usage etc) are showing fine.
The Do I need to add something to the var query URL? I've post the JavaScript and relevant HTML below:
function getDeviceKnownIssues() {
var txtfurtherinfo = "";
var txtTitleKnown = "<ol>";
var query = "**http://example.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc//Knownissues?$filter=DeviceID eq " + window.DeviceId + ** "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function(data, textStatus, jqXHR) {
console.log(JSON.stringify(data));
$.each(data.d.results, function(index, item) {
txtTitleKnown += "<li>" + item.Title + "</li>";
if (item.Info != undefined) {
txtfurtherinfo += item.Info + "\r\n";
}
});
txtTitleKnown = txtTitleKnown + "</ol>";
$('#knowntitle').append(txtTitleKnown);
$('#furtherinfo').append(txtfurtherinfo);
});
call.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error retrieving data: " + jqXHR.responseText);
});
}
<tr>
<td class="tg-yw4l" colspan="3">
<h2>Known Issues</h2>
<div id="knowntitle"></div>
<input type=button onClick="location.href=**'http://example.com/sites/it/ITInfrastructure/_layouts/listform.aspx?PageType=8&ListId={5968ECC4-3049-4794-B6DC-130763C01043}&RootFolder=**'" value='Submit a known issue'>
</td>
<td class="tg-yw4l" colspan="3">
<h2>Accessories</h2>
<div id="deviceacc"></div>
</td>
</tr>
<tr>
<td class="tg-yw4l" colspan="3">
<h2>Typical Usage</h2>
<div id="deviceuse"></div>
</td>
<td class="tg-yw4l" colspan="3">
<h2>Current Status</h2>
<div id="imageContainer"></div>
</td>
</tr>
<td class="tg-yw4l" colspan="3">
<h2>Further Information</h2>
<div id="furtherinfo"></div>
</table>
It seems that you have basic html syntax error.
I would start from that.
You are not opening and closing your 'table row' <tr> and 'table data' <td> tags properly. Should be like this:
[...]
<tr>
<td class="tg-yw4l" colspan="3">
<h2>Further Information</h2>
<div id="furtherinfo"></div>
</td>
<td class="tg-yw4l" colspan="3">
</td>
</tr>
</table>

Display ajax response in Table

display.html :
<div id="display_result" style="display: none"><table class="table">
<p style="float: right;" >Select All<input type="checkbox" class="allcb" data-child="chk" checked/> </p>
<thead>
<tr>
<th>Die No</th>
<th> Status </th>
<th> Location </th>
<th>Select</th>
</tr>
</thead>
<tbody>
</table>
<div id ="issue_button">
<input type="submit" id="submit" class="btn btn-success " value="Recieve" style="width: 150px;"></div>
</div>
Ajax:
var data = JSON.stringify($("#form").serializeArray());
// alert(data);
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: 'POST',
data: {
list: data
},
url: 'die_recieving_process.php',
success: function(data) ){
$('#display_result').html(data);
}
});
die_recieving_process.php
while($fetch = mysql_fetch_array($query))
{
if($fetch[1] == "Table Rack" )
{
echo '<tr class="success"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] </td> </tr>';
}
else
{
echo '<tr class="warning"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] checked </td> </tr>';
}
}
Hi friends in display.html I have to display the result processed in die_recieving_process.php . In ajax i've sent all the value to die_recieving_process.php and after fetching the result i've to display the result in display.html
First in you Javascript, you have 2 errors:
Your code overrides existing contents of div, which is the whole table...
And you have one unnecessary bracket in success function declaration
So change this:
success: function(data) ){
$('#display_result').html(data);
}
To this:
success: function(data) {//remove unnecessary bracket
$('#display_result tbody').html(data);//add data - to tbody, and not to the div
}
By the way, using $.post() you can write your javascript code shorter, like this:
var data = JSON.stringify($("#form").serializeArray());
$.post('die_recieving_process.php',{list:data},function(responseData){
$('#display_result tbody').html(responseData); //added to tbody which is inside #display_result
$('#display_result').show();
});
Second you need to close your tbody tag inside the table
Create html table with empty body tags and body id = tBody for example:
<table>
<caption>Smaple Data Table</caption>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
Use the jquery ajax to load json data in the created table after load button is clicked assuming that my json file is storing userData like userName, age, city:
$('#btnLoadAll').click(function () {
$.ajax({
url: "url/data.json",
dataType: 'json',
success: function (resp) {
var trHTML = '';
$.each(resp, function (i, userData) {
trHTML +=
'<tr><td>'
+ userData.userName
+ '</td><td>'
+ userData.age
+ '</td><td>'
+ userData.city
+ '</td></tr>';
});
$('#tBody').append(trHTML);
},
error: function (err) {
let error = `Ajax error: ${err.status} - ${err.statusText}`;
console.log(error);
}
})
});
If you do not see result, try to remove style="display: none" in display.html

Why is my Ajax code building an empty <tr> as first item?

Im receiving the following JSON object:
[Object, Object, Object]
0: Object
a: "a"
b: "b"
c: "c"
__proto__: Object
1: Object
a: "a"
b: "b"
c: "c"
__proto__: Object
2: Object
a: "a"
b: "b"
c: "c"
__proto__: Object
length: 3
__proto__: Array[0]
With the following ajax code:
function describeItems() {
var html;
var loadingContainer = $("<div class='containerLoading'></div>");
var emptyContainer = $('<div class="emptyContainer"><div style="width: 400px; margin-left:20px;"><h4>Let\'s get started!</h4>You do not have anything in your bucket.<br \>Click the shop button to start shopping items.<button style="margin-top: 20px;" class="btn btn-large btn-primary" type="button" data-toggle="modal" data-target="#shop-items">Shop Items</button></div></div>');
$("#items-table").append(loadingContainer.fadeIn(100));
$.ajax( {
type: "POST",
url: "function.php",
data: {action: 'test'},
dataType: "json",
cache: "false",
success: function(data) {
// DEBUG
console.log(data)
if (data != null)
{
// DEBUG
//console.log(data);
html = html + '<tr>';
html = html + '<td><input type="checkbox" value=""></td>';
$.each(data, function(key,value) {
if (!$.isPlainObject(value)) {
html = html + '<td>' + value + '</td>';
};
});
html = html + '</tr>';
$.each(data, function(key,value) {
html = html + '<tr>';
html = html + '<td><input type="checkbox" value=""></td>';
if ($.isPlainObject(value)) {
// DEBUG
//console.log(value);
$.each(data[key], function(key, value) {
html = html + '<td>' + value + '</td>';
});
};
html = html + '</tr>';
});
html = html + '</tbody>';
// ADD THE HTML TO THE DIV.
$('#innerContent').html(html);
// WHEN LOADING IS DONE, REMOVE OVERLAY.
$("#item-table .containerLoading").fadeOut(100, function() {
$(this).remove();
});
}
else
{
// WHEN LOADING IS DONE, REMOVE OVERLAY.
$("#item-table .containerLoading").fadeOut(100, function() {
$(this).remove();
});
$("#item-table").append(emptyContainer.fadeIn(100));
}
}, // END OF SUCCESS
error: function (xhr, ajaxOptions, thrownError) {
alert('Response Code: ' + xhr.status);
alert(thrownError);
alert(xhr.responseText);
}
}); // END OF $.AJAX
};
But somehow my html table has an empty <tr> in it, at least it has not object content in it..:
<table class="table table-striped table-condensed">
<thead>
<tr>
<th></th>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
</thead>
<tbody id="innerContent">
<tr>
<td>
<input type="checkbox" value="">
</td>
</tr>
<tr>
<td>
<input type="checkbox" value="">
</td>
<td>
a
</td>
<td>
b
</td>
<td>
c
</td>
</tr>
<tr>
<td>
<input type="checkbox" value="">
</td>
<td>
a
</td>
<td>
b
</td>
<td>
c
</td>
</tr>
<tr>
<td>
<input type="checkbox" value="">
</td>
<td>
a
</td>
<td>
b
</td>
<td>
c
</td>
</tr>
</tbody>
</table>
What do I need to change to remove the first empty <tr>?
This loop doesn't produce any TD other than the one with checkbox
html = html + '<tr>';
html = html + '<td><input type="checkbox" value=""></td>';
$.each(data, function(key,value) {
if (!$.isPlainObject(value)) {
html = html + '<td>' + value + '</td>';
};
});
html = html + '</tr>';
Your data is an array, each element of array is an object .
if (!$.isPlainObject(value)) is always false but you are creating the row anyway

jqgrid can't display data from a variable

I have here a javascript code. What I want is that I want to store the data result from this url:
'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)), to my variable 'tempIncDed', and display that data in my jqgrid.
My question here now is, why is that though when i alert the variable tempIncDed, it shows that it stores the correct data, but it does not display in my jqgrid?
Did I miss something in my code?
Below is my js code:
var tempIncDed = [];
$(document).ready( function() {
$("#tblIncDed").jqGrid({ data: tempIncDed,
datatype: "local",
colNames:['Code','Description', 'Taxable','Amount'],
colModel:[
{name:'ded_code',width: 85},
{name:'ded_desc'},
{name:'taxable',width: 95},
{name:'amount', formatter:'currency', align:'right',width: 85}
],
rowNum:20,
viewrecords: true,
rowList:[20,50,100],
ppager: '#tblIncDedPager',
viewrecords: true,
caption: "Details"
});
$( "#btnEarn" ).click(function() {
var empNo = $("#tblPayroll").jqGrid('getCell',($("#tblPayroll").jqGrid('getGridParam', 'selrow')),'emp_no');
var dataTempEarn = {
"SessionID": $.cookie("SessionID"),
"dataType": "data",
"per_id":$("#payPeriod").val(),
"emp_no":empNo
};
$.ajax({
type: 'GET',
url:'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
var resLen = data.result.length;
tempIncDed = JSON.stringify(data.result);
alert('this is the tempDed ' + tempIncDed);
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempIncDed}
).trigger("reloadGrid");
}
}
});
$("#dialOtherIncDed").dialog( "open" );
$("#dialOtherIncDed").attr("name","earnings");
});
})
This is the tempDed sample data: [{"ded_id":"10000000845","ded_code":"100","ded_desc":"MEAL ALL","taxable":"N","amount":"10"},{"ded_id":"10000000849","ded_code":"101","ded_desc":"TRANSPORTATION","taxable":"N","amount":"40"},{"ded_id":"10000000851","ded_code":"103","ded_desc":"LAUNDRY","taxable":"N","mOther_amnt":"50.00"}]
Some of my html code:
<!--master grid-->
<div style="width:100%">
<table id="tblPayroll"></table>
<div id="tblPayrollPager"></div>
</div>
<!--dialog that contains the table for other earnings, deductions, loans-->
<div id="dialOtherIncDed" style="width:100%">
<table id="tblIncDed"></table>
<div id="tblIncDedPager"></div><br><br>
Total amount: <b><span id="totalAmnt"></span></b>
</div>
<!--dialog that contains the dialog edit earnings, deductions, loans-->
<div id="editIncDed"">
<table>
<tr>
<span id="incDed_name"></span>
<td>Amount:</td>
<td><input class="numeric" type="text" id="amount" value = ""/></td></tr>
</table>
</div>
<!--edit-->
<div id="dialogPayrollEdit" title="Payroll Entry">
<table>
<tr>
<td>Payroll Period:</td>
<td><b><span id="periodDateL" style="color:blue"></span></b></td>
<td>Type:</td><td><b><span id="rateType" style="color:blue"></span></b></td>
<td>Rate:</td><td><b><span id="payRate" style="color:blue"></span></b></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><b><span id="empName" style="color:blue"></span></b></td>
</tr>
</table>
<hr/>
<fieldset><legend>Payroll Details</legend>
<p><center><b>EARNINGS</b></center></p>
<table>
<tr>
<td>
....
</td>
<td>
<table >
<tr...tr>
<tr>...</tr>
<tr>...</tr>
<tr><td>Other earnings</td><td><input class="numeric" style="width:60px" id="mOther_amnt" value = ""/></td><td><input type='button' value='...' id="btnEarn"></td></tr>
<tr><td><b>GROSS PAY</b></td><td></td><td><b><span style="width:60px;color:blue" id="grossPay"/></b></td></tr>
</table>
</td>
</tr>
</table>
<hr/>
<p><center><b>DEDUCTIONS</b></center></p>
<table width = "100%">
<tr>
<td>
....
</td>
<td>
<table >
<tr>
<td>Other deductions</td>
<td><input class="numeric" style="width:60px;color:black" id="mOther_ded" value = "" disabled/></td>
<td><input type='button' value='...' id="btnDed"/></td>
</tr>
<tr>
<td>Advances/Loans</td>
<td><input class="numeric" style="width:60px;color:black" id="mLoan_ded" value = "" disabled/></td>
<td><input type='button' value='...' id="btnLoan"></td>
</tr>
<tr></tr>
<tr></tr>
<tr><td><b>NET PAY</b></td><td></td><td><b><span class="numeric" style="width:60px;color:blue" id="netPay" value = "" disabled/></b></td><td></td></tr>
</table>
</td>
</tr>
</table>
<br>
</fieldset><br>
Suggest lowest NET PAY >>> <input type="text" id="lowNetPay" value = "" style="width:80px;color: black" value='0.00' disabled/>
</div><br><br>
<br><br>
<button id="btnPayrollEdit">Edit</button>
The btnLoan, btnDed, and btnEarn will be using the same grid. I also used the variable tempIncDed to save the returned data from ajax..
I've finally solved my own problem. Lets say for example I have this data stored in var tempInc,
[{"ded_id":"10000000845","ded_code":"100","ded_desc":"MEAL ALL","taxable":"N","amount":"10"},{"ded_id":"10000000849","ded_code":"101","ded_desc":"TRANSPORTATION","taxable":"N","amount":"40"},{"ded_id":"10000000851","ded_code":"103","ded_desc":"LAUNDRY","taxable":"N","mOther_amnt":"50.00"}]
This data was an output from ajax request, when the button btnEarn is click.
Here's my javascript code of btnEarn.
var tempInc = []; // global variable
$( "#btnEarn" ).click(function() {
$("#tblIncDed").clearGridData();
var empNo = $("#tblPayroll").jqGrid('getCell',($("#tblPayroll").jqGrid('getGridParam', 'selrow')),'emp_no');
var dataTempEarn = {
"SessionID": $.cookie("SessionID"),
"dataType": "data",
"per_id":$("#payPeriod").val(),
"emp_no":empNo
};
$.ajax({
type: 'GET',
url:'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)),
dataType: primeSettings.ajaxDataType,
success: function(data) {
var tempIncDed = [];
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data.result, function(rowIndex, rowDataValue) {
var fldName = rowDataValue;
tempInc[rowIndex] = fldName;
});
var resLen = data.result.length;
$("#totalAmnt").text(data.result[resLen -1].mTot_amnt);
$("#disTemp").text((JSON.stringify(tempInc)));
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempInc}
).trigger("reloadGrid");
}
}
});
$("#dialOtherIncDed").dialog( "open" );
$("#dialOtherIncDed").attr("name","earnings");
});
Everytime I click that button, it will send ajax request to the server. The data returned (particularlly the object since i have an array of objects) will be saved in global variable, tempInc. After that, I have this code:
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempInc}
).trigger("reloadGrid");
that will display the tempInc in my jqgrid. Hope this will help someone out there.

Categories