Problem
Hi all, I am trying to refresh my table data on a set interval of 10 seconds... problem is that when I initially load the page there is a delay of 10 seconds before my table is shown...
Code
markup
<h2>Employee List</h2>
<!-- table -->
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
<td>ID</td>
<td>Emplyee Name</td>
<td>Address</td>
<td>Created at</td>
<td>Action</td>
</tr>
</thead>
<!-- table content dynamically generated by the javascript -->
<tbody id="showdata"></tbody>
<!-- end content -->
</table>
<!-- end table -->
jQuery
$(function(){
pollServer();
function pollServer(){
window.setTimeout(function () {
alert('hey');
$.ajax({ // this is a json object inside the function
type: 'ajax',
url: '<?php echo base_url('employee/showAllEmployee'); ?>',
async: false,
dataType: 'json',
success: function(data){
console.log(data);
var html = '';
var i;
for(i = 0; i < data.length; i++){
html += '<tr>' +
'<td>' + data[i].employee_id + '</td>' +
'<td>' + data[i].employee_name + '</td>' +
'<td>' + data[i].address + '</td>' +
'<td>' + data[i].created_at + '</td>' +
'<td>' +
'<div class="pull-right">' +
'<a class="btn btn-info btn-xs item-edit" href="javascript:;" data="' + data[i].employee_id + '">Edit</a>' +
'<a class="btn btn-danger btn-xs item-delete" href="javascript:;" data="' + data[i].employee_id + '"><i class="fa fa-times"></i></a>' +
'</div>' +
'</td>' +
'</tr>'
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
},
complete: function(){
pollServer();
}
})
}, 10000);
}
});
Question
How do I get my data on page load, and then ping the server every 10 seconds thereafter?
change pollServer as follows
function pollServer(){
$.ajax({ // this is a json object inside the function
// removed for clarity
complete: function(){
setTimeout(pollServer, 10000);
}
});
}
Just call the same function inside it's success callback with a timeout.
function pollServer() {
$.ajax({
...
success: function(data) {
setTimeout(function() {
pollServer();
},10000);
}
});
}
// Call the function on load
pollServer();
Related
I have an AJAX post that returns a data set. this part works completely fine.
However when building the table in the success area of the AJAX GET i create a Checkbox for each row.
When i then carry out an "On Click" Event of the checkbox it doesn't work.
Here is the AJAX/Table creation
function ListAppointments() {
$.ajax({
type: "GET",
url: "../Appointments",
data: { 'id': id },
contentType: "application/json; charset=UTF-8",
dataType: "json",
success: function (response) {
if (response.length > 0) {
$.each(response, function (i, item) {
var apptDate, apptTime, arrivalTime = "";
if (item.ApptDateTime != null) {
apptDate = moment(item.ApptDateTime).format('DD-MMM-YYYY');
apptTime = moment(item.ApptDateTime).format('HH:mm');
}
var row = '<tr class="grid__row--select"' + item.ID + '">' +
'<td><input id="check" name="check" id="chk" class="chkBoxOPA" type="checkbox" value="' + item.ID + '"/></td>' +
'<td style = "white-space:nowrap;">' +
'<div class="media-left">' +
'</div>' +
'<div class="media-body">' +
'<h3 class="list-group-item-heading">' + item.DisplayName + '</h3>' +
'<span class="list-group-item-text">' + item.DisplayDOB + ' (' + item.DisplayAge + ')</span>' +
'</div>' +
'</td>' +
'<td class="text-center" style="white-space:nowrap;">' +
'<span class="list-group-item-heading">' + apptDate + '</span>' +
'<span class="list-group-item-text">' + apptTime + '</span>' +
'</td>' +
'<td>' +
'<span class="grid__row--smaller-text">' + item.OutcomeDesc + '</span>' +
'</td>' +
'<td class="text-center" style="white-space:nowrap;">' +
'<span class="grid__row--smaller-text">' + arrivalTime + '</span>' +
'</td>' +
'</tr>';
$('#appointments-body').append(row);
});
}
else {
console.log(JSON.stringify(response));
}
},
error: function (response) {
console.log(JSON.stringify(response));
}
});
}
When i then try to do this
$(".chkBoxOPA").on("change", ":checkbox", function () {
alert('test');
});
It doesnt seem to bind or work.
The ListAppointments function is run on a button click event.
You added rows dynamically so use document
$(document).on("change", ".chkBoxOPA", function () {
alert('anything');
});
OR if you dont want to use class then use as
$(document).on("change", "input[type=checkbox]", function () {
alert('anything');
});
.chkBoxOPA and :checkbox refers to the same element but with your selector you are looking for :checkbox inside .chkBoxOPA and the selector fails to target the check box. You can find the element .chkBoxOPA inside tr.
Please Note: The attribute id must be unique in document.
Try:
$("tr").on("change", ".chkBoxOPA", function () {
alert('test');
});
Demo:
var checkbox = `<td><input name="check" class="chkBoxOPA" type="checkbox" value="item1"/></td>`;
$('tbody tr').append(checkbox); //add check box dynamically
$("tr").on("change", ".chkBoxOPA", function () {
alert('The index is: ' + $(".chkBoxOPA").index(this));
});
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Check</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
</tr>
</tbody>
</table>
Ajax is Asynchronous And when you write This Code
$(".chkBoxOPA").on("change", ":checkbox", function () {
alert('test');
});
that checkbox didn't add to table Then you have to solution first
$.ajax({
.....
async:false,
.....
})
or you can use this solution
......
$('#appointments-body').append(row);
$(".chkBoxOPA").on("change", ":checkbox", function () {
alert('test');
});
.......
I'm calling on two urls to get data and put on a table. Problem is, when there's only one ajax call everything is loaded in order it's supposed to. When there're two, all hell breaks loose.I started with promises but was told it wasn't a good idea [edit1] the way i was implementing it. suggestions please?
example of code:
$.ajax({
"url":url1,
"crossDomain":true,
"dataType":"jsonp",
'success': function(response){
var datee = response.results.collection1[0].date;
var collection = response.results.collection2;
$(".table-group1").append('<tr><td class=well">'+ datee.substr(56,60) +'</td></tr>');
for (var i = 1; i < collection.length; i++){
$(".table-group1").append('<tr>' + '<td class="well">' + collection[i].domain.href + '</td>' + '<td class="well">' + collection[i].dns + '</td>' + '<td class="well">' + collection[i].mail + '<td class="well">' + collection[i].web + '</td>' +'</tr>');}},
error: function(err){
alert('error!' + err);
}
});
$.ajax({
"url":url2,
"crossDomain":true,
"dataType":"jsonp",
'success': function(response){
var datee = response.results.collection1[0].date;
var collection = response.results.collection2;
$(".table-group1").append('<tr><td class=well">'+ datee.substr(56,60) +'</td></tr>');
for (var i = 1; i < collection.length; i++){
$(".table-group1").append('<tr>' + '<td class="well">' + collection[i].domain.href + '</td>' + '<td class="well">' + collection[i].dns + '</td>' + '<td class="well">' + collection[i].mail + '<td class="well">' + collection[i].web + '</td>' +'</tr>');
}},
error: function(err){
alert('error!' + err);
}
});
Desired output is a table with two columns for each property (domain, dns, email web) from both url1 and url2.
html table:
<div class= "container_1">
<table class="table" border="1">
<th class="panel-heading"> </th>
<tr class="domain"> </tr>
<tr class="table-group1">
</tr>
</table>
Here's how you'd handle the ajax side
var p1 = $.ajax({
url: url1,
crossDomain: true,
dataType: "jsonp"
});
var p2 = $.ajax({
url: url2,
crossDomain: true,
dataType: "jsonp"
});
Promise.all([p1,p2])
.then(function(results) {
//results[0] is the the same as response in your code for url1
//results[1] is the the same as response in your code for url2
});
As you now have all the data at hand, you should be able to format the output as you require
If you want to sequence your two ajax calls so one finishes before the other is started, just do this;
$.ajax(...).then(function() {
return $.ajax(...);
}).then(function(){
// both are done here
});
I am new in Bootstrap JS. I have a table made with Bootsrap JS, whose data came from a Json file. Here is The Code-
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="fixedscroll">
<table id="user_table" class="table table-hover table-bordered table-striped responsive" style="margin-bottom: 0;" class="display">
<thead>
<tr>
<th>UID</th>
<th>Name</th>
<th>Address</th>
<th>Tags</th>
<th>Edit tags</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
function showAll(){
$.ajax({
url: "showAll",
dataType:"json",
success:function(data){
$('#user_table tr:gt(0)').remove();
jQuery.each(data['Payload'], function(index, value) {
var row = '<tr>'
+ '<td id="tduid">'+ value['uid']+ '</td>'
+ '<td>'+ value['name']+ '</td>'
+ '<td>'+ value['address']+ '</td>'
+ '<td>'+ value['tag1']+ ',' + value['tag2']+ ',' + value['tag3']+'</td>' + '<td>'+ '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '</td></tr>';
$('#user_table').append(row);
});
}
});
Now This Payload is the name of my json, which came from a servlet where I call the database.
Now let, there is 3 tags. But some of rows have 2 tags. So, when I put the values in json the Json looks like-
{"Payload":[{"uid":"u01","name":"Subho","address":"Dumdum","tag1":"aircel","tag2":"vodafone","tag3":"airtel"},{"uid":"u02","name":"Jeet","address":"Baruipur","tag1":"airtel","tag2":"","tag3":"aircel"},{"uid":"u03","name":"Diba","address":"Jadavpur","tag1":"vodafone","tag2":"aircel","tag3":"airtel"},{"uid":"u04","name":"Tommy","address":"Baguihati","tag1":"aircel","tag2":"vodafone","tag3":""},{"uid":"u05","name":"Jonty","address":"Rahara","tag1":"","tag2":"vodafone","tag3":"airtel"},{"uid":"u06","name":"Gourav","address":"Tripura","tag1":"aircel","tag2":"vodafone","tag3":"airtel"}]}
Now You can see, that for UID=U02 there is 2 tags. And the output looks like picture attached. How can I remove the blank values or null values???? Please anyone help me...
I think, you are saying about the extra , in the tags column... one messy solution is
$.ajax({
url: "showAll",
dataType: "json",
success: function (data) {
$('#user_table tr:gt(0)').remove();
jQuery.each(data['Payload'], function (index, value) {
var tags = $.map([value.tag1, value.tag2, value.tag3], function (value) {
return value || undefined;
});
var row = '<tr>' + '<td id="tduid">' + value['uid'] + '</td>' + '<td>' + value['name'] + '</td>' + '<td>' + value['address'] + '</td>' + '<td>' + tags + '</td>' + '<td>' + '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '</td></tr>';
$('#user_table').append(row);
});
}
});
As #Alnitak said
var tags = [value.tag1, value.tag2, value.tag3].filter(function (value) {
return value !== undefined;
});
console.log(tags)
I'm trying to create a single-page app that pulls information from a JSON file, displays it on the screen, and perform a few actions.
Right now, I have all of the information being displayed on the screen properly: http://jsfiddle.net/rcsayf7t/3/
I need the "Remove" button to asynchronously remove the JSON object from the screen when it's clicked, but unfortunately have no idea how to go about accomplishing it.
HTML:
<table>
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Name</th>
<th scope="col">Message</th>
<th scope="col">Date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody class="tweets-result"></tbody>
</table>
jQuery:
// helper function for formatting date
function formatDate(date) {
var dateSplit = date.split(" ");
var displayDate = dateSplit[0] + ", " + dateSplit[1] + " " + dateSplit[2];
// return the result
return displayDate;
}
$(document).ready(function () {
// start ajax request
$.ajax({
url: "https://gist.githubusercontent.com/arlodesign/7d80edb6e801e92c977a/raw/24605c9e5de897f7877b9ab72af13e5b5a2e25eb/tweets.json",
dataType: "text",
success: function (data) {
// store the JSON data
var tweetData = $.parseJSON(data);
// loop through json values and build the table
$.each(tweetData.tweets, function (index, item) {
$('.tweets-result').append(
'<tr>' +
'<td><img src="' + item.profile_image_url + '" alt="#' + item.screen_name + ' avatar"></td>' +
'<td>#' + item.screen_name + '</td>' +
'<td>' + item.text + '</td>' +
'<td>' + formatDate(item.created_at) + '</td>' +
'<td>Remove</td>' +
'</tr>');
// WHEN YOU CLICK "REMOVE", THE TWEET SHOULD
// ASYNCHRONOUSLY BE REMOVED FROM THE SCREEN
});
}
});
});
Live demo
Just add the following inside ajax success:
$('.remove_row').click(function(){
$(this).closest('tr').remove();
});
and the following code as remove attribute:
class="remove_row"
Full JS (read my comments):
// helper function for formatting date
function formatDate(date) {
var dateSplit = date.split(" ");
var displayDate = dateSplit[0] + ", " + dateSplit[1] + " " + dateSplit[2];
// return the result
return displayDate;
}
$(document).ready(function () {
// start ajax request
$.ajax({
url: "https://gist.githubusercontent.com/arlodesign/7d80edb6e801e92c977a/raw/24605c9e5de897f7877b9ab72af13e5b5a2e25eb/tweets.json",
dataType: "text",
success: function (data) {
// store the JSON data
var tweetData = $.parseJSON(data);
// loop through json values and build the table
$.each(tweetData.tweets, function (index, item) {
$('.tweets-result').append(
'<tr>' +
'<td><img src="' + item.profile_image_url + '" alt="#' + item.screen_name + ' avatar"></td>' +
'<td>#' + item.screen_name + '</td>' +
'<td>' + item.text + '</td>' +
'<td>' + formatDate(item.created_at) + '</td>' +
'<td class="remove_row">Remove</td>' + // ## Here add the class remove_row
'</tr>');
// WHEN YOU CLICK "REMOVE", THE TWEET SHOULD
// ASYNCHRONOUSLY BE REMOVED FROM THE SCREEN
});
//## Here assign the even on click for the remove button
$('.remove_row').click(function(){
$(this).closest('tr').remove();
});
}
});
});
I'm creating a 'live' leaderboard table. Every X seconds, an AJAX request is sent to the server to load the latest leaderboard data.
If there's a change in data, the leaderboard will instantly update upon the AJAX request.
However - If there IS a change, instead of instantly showing the new data, I want to animate the table row to its new position instead of instantly reloading it. What is the best way of achieving something like this?
I'm updating the leaderboard at the moment like so:
$(document).ready(function() {
showLeaderboard();
if (autoUpdate != false) {
window.setInterval(function(){
$('#wrapper h2, #leaderboard tbody tr').remove(updateLeaderboard());
}, reloadInterval);
}
});
function updateLeaderboard() {
leaderBoardType;
numRecords;
quizIDs;
topListTitle;
latestTitle;
$.webMethod({
url: 'xxx',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
type: 'POST',
cache: false,
beforeSend: function () {
$('body').append('<div class="loading"></div>');
},
success: function (ret)
{
$('.loading').remove();
$('#wrapper').prepend(topListTitle);
$.each(ret.leaderboard,function(i){
pos = i + 1;
str = '<td class="position">' + pos + '</td>';
str += '<td class="name">' + ret.leaderboard[i].first_name + ' ' + ret.leaderboard[i].last_name + '</td>';
str += '<td class="time">' + getTime(ret.leaderboard[i].time_taken) + '</td>';
str += '<td class="points">' + ret.leaderboard[i].points + '</td>';
//str += '<td>' + ret.leaderboard[i].last_name + '</td>';
//str += '<td>' + ret.leaderboard[i].incorrect_attempts + '</td>';
//str += '<td>' + ret.leaderboard[i].user_id + '</td>';
$('#leaderboard tbody').append('<tr>'+str+'</tr>');
});
},
error: function (response) { alert(response.responseText); }
});
}
HTML
<table id="leaderboard">
<thead>
<tr>
<th class="position">Position</th>
<th class="name">Name</th>
<th class="time">Time Taken</th>
<th class="points">Points</th>
</tr>
</thead>
<tbody>
</tbody>
</table>