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();
}
}
});
}
Related
I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>
When onclick the status update then only corresponding row should be refresh . before that i written the drop down onchange function based on that only table row is display.
cs.html:
<section class="card ">
<div class="card-block">
<h5 class="with-border m-t-lg">View Module List</h5>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label" for="exampleInput">Domain Name</label>
#Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { #class = "select2-arrow" })
</fieldset>
</div>
</div>
<br />
<div class="table-responsive" id="findValue" style="display:none;">
<table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
<thead>
<tr>
<th>S#</th>
<th>Module Name</th>
<th>Url</th>
<th>Roles</th>
<th>Action</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
Dropdown based on view tables code:
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
var Status = '';
if (item.Status == "Y") {
Status = '<img src="/img/Active.png" height="22" width="42"/>'
} else {
Status = '<img src="/img/InActive.png" height="22" width="42"/>'
}
var rows = "<tr>"
+ "<td>" + (i + 1) + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + ' ' + Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
Update status Code
<script>
$(document).ready(function () {
$("#example tbody").on('click', '.user-status', function () {
var getId = $(this).data('id');
var status = $(this).attr('data-status');
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateStatusModule")',
dataType: 'json',
data: { ModuleID: getId },
success: function (data) {
if (data.success) {
alert(data.message);
$("#example tbody").load("/Account/UpdateStatusModule");
}
},
error: function (ex) {
alert('Failed to retrieve Sub Categories : ' + ex);
}
});
});
});
</script>
i written the drop down onchange function based on that only table row is display. When onclick the status update then only corresponding row should be refresh onchange no value should not be change
#region Update Status
[Authorize]
[HttpPost]
public ActionResult UpdateStatusModule(int ModuleID)
{
try
{
int refID = Convert.ToInt32(Session["RefID"]);
int typeID = Convert.ToInt32(Session["ComTypeID"]);
if (ModelState.IsValid && refID > 0)
{
userType type = new userType();
type.UpdateStatusModule(ModuleID);
}
return Json(new { success = true, message = "updated successfully" }, JsonRequestBehavior.AllowGet);
}
catch
{
return View();
}
}
#endregion
If you append html after the initialization it can't work.
You need to register events on document(without $(document).ready)
$(document).on("change","#DomainID", function () {
alert("domain changed");
}).on('click', '.user-status', function () {
alert("clicked");
});
For async POST:
$.post("MyUrl",{myId: myId},function(data){
do wathever
}).fail(function(x,y,z){
alert("ops");
});
More simple
I make calculations in the rows of the table. But I have some problems. Let's look at the picture below.
It was supposed to be 26.8. Every time I click on the last row I get the data on the line.
I forgot to add the codes yesterday. sorry
<script type="text/javascript">
$(function () {
$(document).ready(function () {
$(".AddRow").click(function () {
var id = $(this).attr("data-id");
var row = $('#deger tr:last');
$.ajax({
async: true,
url: '/Home/Ekle/' + id,
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (besin) {
//I create the rows of the table
$("#deger tr:last").before("<tr><td style='height:30px;line-height:30px'>" + besin.BesinAd +
"</td><td style='height:30px;line-height:30px'>" + besin.KHDeger + "x" + besin.KHGram +
"</td><td style='height:30px;line-height:30px' class='hKh'>" + besin.KHDeger +
"</td><td style='height:30px;line-height:30px' class='hGr'>" + besin.KHGram +
"</td><td style='height:30px;line-height:30px'><input type='text' class='form-control input-xs txtHesap'></input></td><td style='height:30px;line-height:30px'><button class='btn btn-success btn-xs sil'>Sil</button></td></tr>");
$(".txtHesap").focus();
/*Actions to be performed when a value is entered in the textbox
Where only the last added line gets its value. That's my problem.*/
$("#deger").on('input', '.txtHesap', function () {
var toplam = 0;
var khgr = besin.KHGram; //Values from the controller
var kh = besin.KHDeger; //Values from the controller
$("#deger .txtHesap").each(function () {
var gr = $(this).val();
if ($.isNumeric(gr)) {
toplam += parseFloat((gr * kh) / khgr);
}
});
$("#toplam").html(toplam.toFixed(2));
});
}
});
});
});
});
I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle
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);
}