My table tbody doesn't display the correct data after an AJAX GET request. Well actually, after the second iteration of my for loop, it is showing correctly, but after the third iteration and so on, it is appending but it is showing the previous item.
This is what it showing:
I don't know why it is showing incorrectly in the table in console log, the data is showing correctly.
$.ajax({
cache: false,
type: 'GET',
url: '#Url.Action("DisplayFiles","FileUploader")', //url, // '/Account/Delete/',
dataType: "json",
success: function(response) {
$("#tblFiles tbody").remove();
for (var i = 0; i < response.length; i++) {
console.log(response[i]['Filename']);
console.log(response[i]['FileFullPath']);
$("#tblFiles").append('<tr><td>' + response[i]['Filename'] + '</td><td>' + response[i]['FileFullPath'] + '</td></tr>');
//var tbodyFiles = "<tr><td> " + response[i]['Filename'] + "</td>" + "<td> " + response[i]['FileFullPath'] + "</td></tr>";
}
//$("#tblFiles").append(tbodyFiles);
console.log(response);
},
error: function(resp) {
console.log('error');
}
});
<table class="table table-striped" id="tblFiles">
<thead>
<tr>
<th>Filename</th>
<th>File Fullpath</th>
#*
<th>Date Added</th>*#
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Filename)
</td>
<td>
#Html.DisplayFor(modelItem => item.FileFullPath)
</td>
#*
<td>
#Html.DisplayFor(modelItem => item.DateAdded)
</td>
*#
<td>
#Html.ActionLink(" ", "Delete", new { id = item.Id }, new { #class = "btn-xs btn btn-danger glyphicon glyphicon-trash" })
</td>
</tr>
}
</tbody>
</table>
Change this:
$("#tblFiles tbody").remove();
to this:
$("#tblFiles tbody tr").remove();
and then change this:
$("#tblFiles").append(...)
to this:
$('#tblFiles tbody").append(...)
Explanation:
You were removing the entire tbody element, but appending the trs to the table not the tbody.
The proposed changes will ensure that the tbody stays present and that trs are added as children to it instead of outside of it.
Related
On my view page I have a table (from a partial view) and a form. I am using ajax to submit the form to my webapi controller.
On success I would like to add what was entered in the textbox to the first column, and links to Edit and Delete in the second column of a new row.
As of right now I am only working on the Edit link.
Here is my partial view table:
<table id="Table" class="table table-bordered">
<thead>
<tr>
<th class="col-md-6">
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
#foreach (var item in Model)
{
<tr>
<td class="col-md-6">
#Html.DisplayFor(modelItem => item.Admin)
</td>
<td class="col-md-6">
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
Here is my form jquery.ajax:
var table = $("#Table").DataTable({
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [1] },
{ "bSearchable": false, "aTargets": [1] }
]
});
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: infoGetUrl,
method: "post",
data: $("form").serialize()
}).success(function (data) {
var editLink = document.createElement('a');
editLink.href = "/controllerName/Edit/" + data.id;
editLink.text = "Edit";
table.row.add([
$("#Textbox").val(),
editLink
]).draw();
}).error(function(jqXHR, textStatus, errorThrown) {
console.log("error");
});
});
The problem is that when this renders I get this:
It is not clickable and renders like this:
<tr class="even" role="row">
<td class="sorting_1">John.Doe</td>
<td>http://localhost:61888/controllerName/Edit/15</td>
</tr>
As you can see, it is not rendered in an a tag, and I don't need the http://localhost:61888 part of the link.
How can I resolve this?
try creating link as:
var link = <a href='/controllerName/Edit/' + data.id>EDIT</a>
With pur JS:
var link = document.createElement('a');
link.textContent = 'Edit';
link.href = "/controllerName/Edit/" + data.id;
you just need to place this inside your td.
If you want to remove 'http://localhost:61888' you can just use replace to change your localhost by un empty string. Or split your string and just keep the second part
I am trying to attach multiple rows dynamically ( as per the results fetched from the database) to the existing table.
my html code
<table width="100%" border="1" class="queriedResponders">
<tbody>
<tr>
<th><strong>Select</strong></th>
<th><strong>Responder Name</strong></th>
<th><strong>Responder Company</strong></th>
<th><strong>Responder Number</strong></th>
<th><strong>City</strong></th>
<th><strong>Distance(Km)</strong></th>
</tr>
</tbody>
</table>
my jQuery code
$.ajax({
data: data,
url: url,
type: 'POST',
datatype: 'JSON',
success: function (response) {
console.log(response);
var result = $.parseJSON(response);
var count = result.length;
for (var i = 0; i < count; i++) {
var $row = $("<tr><td><input type='radio' name='assignRadio'></td><td>" + result[i].name + "</td><td> Murgency Global Network</td><td>" + result[i].number + "</td><td>" + result[i].city + "</td><td> 0.5 Km</td></tr>");
$('table.queriedResponder > tr:last').append($row);
}
console.log($row);
}
});
});
Please note :- I am getting the desired result as I have console logged the output which is a JSON object like 1 pasted below
[{"name":"mihir panchal","company":"","number":"00919664804737","city":""}]
Please guide me as to where am I making the mistake
2 things:
You are not referencing the correct element. Your table has a class of queriedResponders, and you are targeting queriedResponder
You should be append to the tbody instead of the tr
Both of those things combined results in this:
$('table.queriedResponders tbody:last').append($row);
I've simplified the response to get a working example:
var result = [{
"name": "mihir panchal",
"company": "",
"number": "00919664804737",
"city": ""
}];
var count = result.length;
for (var i = 0; i < count; i++) {
var $row = $("<tr><td><input type='radio' name='assignRadio'></td><td>" + result[i].name + "</td><td> Murgency Global Network</td><td>" + result[i].number + "</td><td>" + result[i].city + "</td><td> 0.5 Km</td></tr>");
$('table.queriedResponders tbody:last').append($row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="100%" border="1" class="queriedResponders">
<tbody>
<tr>
<th><strong>Select</strong></th>
<th><strong>Responder Name</strong></th>
<th><strong>Responder Company</strong></th>
<th><strong>Responder Number</strong></th>
<th><strong>City</strong></th>
<th><strong>Distance(Km)</strong></th>
</tr>
</tbody>
</table>
You are appending the new row to the last tr while you want to append it in <tbody>
so you should replace it with
$('table.queriedResponders > tbody:last-child').append($row);
or if you want to use your last <tr> you may use .after() instead of .append() to add the new row after your last row
$('table.queriedResponders tr:last').after($row);
Solution1: Working Demo
Solution2: Working Demo
I was trying to create a dynamic table with contents from jQuery. Also I have enabled a setTimeout in order for the data to be refreshed and updated in the html page.`
$(document).ready(function update_data() {
$.ajax({
dataType: "json",
url: "/wirelessSensor/dag",
success: updateForData,
error: errorOnAjax
});
setTimeout(function() {
update_data();
}, 5000);
});
function updateForData(data) {
// Updates DAG
console.log("Wirless nodes details");
var hasData = true;
if (data.result && data.result && data.result == "none") {
console.log('No data in result');
hasData = false;
} else if (!data.devices || !data.status) {
console.log('Devices not found in result');
hasData = false;
}
if (hasData) {
console.log('Creating Table');
var trHTML = '';
$.each(data.devices, function(index) {
trHTML += "<tr><td>" + data.devices[index] + "</td><td>" + data.lifetime[index] + "</td><td>" + data.status[index] + "</td></tr>";
});
$("#location").append(trHTML);
}
}
function errorOnAjax(jqxhr, status, errorstr) {
var errText = (errorstr == null) ?
'' : ', error: ' + errorstr;
console.log('Ajax error: ' + status + errText);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="location" border='1' width='100%'>
<tr>
<th align='center'> Devices </th>
<th align='center'> Lifetime </th>
<th align='center'> Status </th>
</tr>
</table>
Here since am using setTimeout my dynamic table is getting duplicated. The entries already existing are been repeated. How can I avoid this?
You can restructure your HTML to include <thead> and <tbody> elements, and the set the contents of the <tbody> to the results (rather than appending results to entries that might already be present).
<table id="location" border='1' width='100%'>
<thead>
<tr>
<th align='center'> Devices </th>
<th align='center'> Lifetime </th>
<th align='center'> Status </th>
</tr>
</thead>
<tbody id="location-content"></tbody>
</table>
Then do $("#location-content").html(trHTML); (note: html instead of append, to destroy old results instead of keeping them)
I am trying to add new rows to the table using the rows.add() function in the DataTables API. The data is coming from the server using AJAX call.
Here is an example to work upon - FIDDLE
My Table Structure is follows:
<table id="myTable">
<thead>
<th>
Id
</th>
<th>
Name
</th>
<th>
Designation
</th>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Number
</td>
<td>
#item.Name
<img id="imgA" onclick="AddNewRows();" class="iterationChild" src="#Url.Content("~/Images/plus.png")" alt="expand/collapse" />
</td>
<td>
#item.Designation
</td>
</tr>
}
</tbody>
</table>
Corresponding Javascript function:
function AddNewRows() {
$.ajax({
type: 'GET',
url: '#Url.Action("NewRows", "Home")',
dataType: "json",
async: true,
success: function (data) {
var table = $('#myTable').DataTable();
for (var i = 0, l = data.length; i < l; i++) {
//how to add it just after the current row clicked
table.row.add([
data[i].Number,
data[i].Name,
data[i].Designation
]).draw();
}
},
error: function (result) {
alert('error');
}
});
}
I want to be able to add the new row after the row which is clicked. Here it is adding at the end of the table(last rows).
Assuming every row as a unique id, try passing the current row clicked id into your function as a parameter. Example:
function AddNewRows(id) {
var my_row = document.getElementById(id);
...
This is my table , I get the data list using json and populate this table,
<table id="tblClaimSearch" class="display responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="ChkboxClaimHeader" name="ChkboxClaimHeader" value="false"></th>
<th>Claim #</th>
<th>Client Name</th>
<th>Amount</th>
<th>Deduction</th>
<th>Type</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My jquery which has Json result, I get the result and append rows to table body based on my data,
$(document).ready(function () {
$.ajax({
url: '#Url.Action("ClaimResultTest", "Claims")',
data: { seacrhClaimNumber: claimNumberToBeSearched },
type: 'POST',
success: function (data) {
var dataClaims = data.Claims;//This has the complete list
for (i = 0; i < dataClaims.length; i++) {
alert(dataClaims[i].ClaimNumber);
$("#tblClaimSearch").find('tbody')
.append($('<tr>')
.append($('<td><input type="checkbox">'))
.append($('<td>').text(dataClaims[i].ClaimNumber))
.append($('<td>').text(dataClaims[i].Client))
.append($('<td>').text(dataClaims[i].Amount))
.append($('<td>').text(dataClaims[i].Deduction))
.append($('<td>').text(dataClaims[i].Type))
.append($('<td>').text(dataClaims[i].Status))
)
}
}
});
});
The problem is when there is no data, I have a row displaying "No data available in table"..And even when there is data appended I still have first row as "No data available in table"..How do I hide this message row when new rows with data have been added??And secondly even though I have 16 entries it still shows "Showing 0 of 0 entries"?.What am I doing wrong?..
try this:-
$(document).ready(function () {
$.ajax({
url: '#Url.Action("ClaimResultTest", "Claims")',
data: { seacrhClaimNumber: claimNumberToBeSearched },
type: 'POST',
success: function (data) {
$("#tblClaimSearch").find('tbody').empty(); //add this line
var dataClaims = data.Claims;//This has the complete list
for (i = 0; i < dataClaims.length; i++) {
alert(dataClaims[i].ClaimNumber);
$("#tblClaimSearch").find('tbody')
.append($('<tr>')
.append($('<td><input type="checkbox">'))
.append($('<td>').text(dataClaims[i].ClaimNumber))
.append($('<td>').text(dataClaims[i].Client))
.append($('<td>').text(dataClaims[i].Amount))
.append($('<td>').text(dataClaims[i].Deduction))
.append($('<td>').text(dataClaims[i].Type))
.append($('<td>').text(dataClaims[i].Status))
)
}
}
});
});