Update table row with animation upon AJAX request - javascript

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>

Related

Pass paramenter to "Show detail" modal in table

I've made the following dynamic table, which rows are created for each record found in database.
$(document).ready(function () {
var $form = $('#my-form');
$form.submit(function () {
$.post($(this).attr('action'), $(this).serialize(), function (response) {
let table = '<table> <thead> <tr> <th>Candidate Name</th> <th>Candidate Surname</th> <th>Interview Type</th> <th>Interview Date</th> <th>Interviewer</th> <th>Feedback</th> </tr> </thead><tbody>';
response.forEach(function (d) {
table += '<tr><td>' + d.candidateName + '</td>';
table += '<td>' + d.candidateSurname + '</td>';
if (d.interviewType === 1) {
table += '<td>MOTIVAZIONALE</td>';
} else if (d.interviewType === 2) {
table += '<td>TECNICO</td>';
} else {
table += '<td></td>';
}
if (d.scheduledDate === null) {
table += '<td></td>';
} else {
table += '<td>' + d.scheduledDate + '</td>';
}
table += '<td>' + d.enterpriseId + '</td>';
if (d.finalFeedback === null) {
table += '<td><button type="button" onclick="sendValue(d.idColloquio)">Add a feedback</button></td></tr>';
}else{
table+= '<td>OK</td></tr>';
}
})
table += '</tbody>';
$('#mytable').empty().html(table);
}, 'json');
return false;
});
});
In each row there is a button used to insert a feedback: this button have to redirect in another page by passing the id as a request parameter, but the "onClick" function doesn't work. On Chrome inspector event in generated.
SendValue:
function sendValue(id) {
window.location.href="insertMotivationFeedback?idColloquio="+id;
}
Anyone can help me?
Thanks
You have to pass complete url:
window.location.href="https://example.com/insertMotivationFeedback?idColloquio="+id;

JSON to HTML Table JavaScript Not Working

JSON to HTML Table JavaScript Not Working
I've written this function to display the contents of the JSON file in an HTML table. However, it's returning as undefined.
I don't seem to be able to work out why this is happening. The console log displays the data just fine, but not the HTML table.
I'm wondering if it has something to do with the way arrays are parsed?
I want to keep the code short and clean, but wondering if there is a better way to do this without the undefined error. Maybe Vanilla JavaScript is better, using fetch?
Live page is found here: LBRYnomics
Thanks in advance!
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub)
var sub_data = '';
$.each(data, function(key, value) {
sub_data += '<tr>';
sub_data += '<td>' + value.ranks + '</td>';
sub_data += '<td>' + value.vanity_names + '</td>';
sub_data += '<td>' + value.claim_ids + '</td>';
sub_data += '<td>' + value.subscribers + '</td>';
sub_data += '</tr>';
console.log(key + '=' + value);
});
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>
You have multiple different arrays for each of those properties.
Assuming they are all in same relationship order you can loop over one of the arrays and use the iteration index to access corresponding elements from each of the other arrays.
Something like:
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub);
var sub_data = '';
$.each(data.ranks, function(i, rank) {
sub_data += '<tr>';
sub_data += '<td>' + rank + '</td>';
sub_data += '<td>' + data.vanity_names[i] + '</td>';
sub_data += '<td>' + data.claim_ids[i] + '</td>';
sub_data += '<td>' + data.subscribers[i] + '</td>';
sub_data += '</tr>';
//console.log(key + '=' + value);
});
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>
I think after inspecting the api it looks the items are put in different array with no connection but they have the same length. So assuming that attrbute1 at index N maps to attribute2 at index N and so on.
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub)
var sub_data = '';
for(var i=0; i<data.ranks.length; i++){
//$.each(data.ranks, function(key, value) {
sub_data += '<tr>';
sub_data += '<td>' + data.ranks[i] + '</td>';
sub_data += '<td>' + data.vanity_names[i] + '</td>';
sub_data += '<td>' + data.claim_ids[i] + '</td>';
sub_data += '<td>' + data.subscribers[i] + '</td>';
sub_data += '</tr>';
//console.log(key + '=' + value);
//});
}
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>

How to remove a null object from json

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)

Asynchronously remove JSON object from screen

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();
});
}
});
});

Problems in Binding To Dynamic Table

I worked on this sample for 3 days strucked at last step!! Please some one help me!!
Any Help is appreciable!!
I am loading a dynamic table, i want to attach a grid on a column. I created a function for binding jqgrid. So when ever i am binding a table i am calling this function with a parameter,
The problem here is if i give the parameter directly it is working , but if i want to load it automatically it is not working.
I will explain below with code:
function bindData() {
$.ajax({
type: "POST",
url: location.pathname + "/getData",
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
var msg = eval('(' + response.d + ')');
if ($('#tblResult').length != 0) // remove table if it exists
{ $("#tblResult").remove(); }
var table = "<table class='tblResult' id=tblResult><thead> <tr><th>Name</th><th>SurName</th><th>Email</><th>Mobile</th><th>Address</th><th>Actions</th><th>image</th><th>Country</th><th>State</th><th>Gender</th><th>Add.Mobile</th></thead><tbody>";
for (var i = 0; i <= (msg.length - 1); i++) {
var row = "<tr>";
row += '<td>' + msg[i].Name + '</td>';
row += '<td>' + msg[i].SurName + '</td>';
row += '<td>' + msg[i].Email + '</td>';
row += '<td>' + msg[i].Mobile + '</td>';
row += '<td>' + msg[i].Address + '</td>';
row += '<td><img id="im" src="/User_Registration1/images/edit.png" title="Edit record." onclick="bindRecordToEdit(' + msg[i].EmployeeId + ')" /> <img src="/User_Registration1/images/delete.png" onclick="deleteRecord(' + msg[i].EmployeeId + ')" title="Delete record." /></td>';
row += '<td><img class="img" src=' + msg[i].FileName + ' alt="--NO IMAGE--"/></td>';
row += '<td>' + msg[i].Country + '</td>';
row += '<td>' + msg[i].StateName + '</td>';
row += '<td>' + msg[i].Gender + '</td>';
row += '<td style="width:250px;height:120px;"><table id="tblSub' + msg[i].Name + '"></table><script> $(document).ready(function () { BindGrid("AjjiAjji");});</script></td>';
row += '</tr>';
table += row;
}
table += '</tbody></table>';
$('#divData').html(table);
$("#divData").slideDown("slow");
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
see the last column in which i am attaching a grid view by calling a javascript function.
js function:
function BindGrid(user) {
$(document).ready(function () {
$("#tblSub"+user).jqGrid({
loadError: function (xhr, status, error) {
alert('load:' + error);
},
url: 'Fetch.aspx?filter=' + user + '',
data: "{}",
datatype: 'json',
colNames: ['Name', 'Mobile'],
colModel: [
{
name: 'User',
index: 'User',
width: 100,
align: "left",
editable: true,
size: 80
},
{
.
.
.
So if i pass the BindGrid("AjjiAjji") it is working fine, But i want to load the grid automatically like BindGrid('+msg[i].Name+') , It is Showing Error "ReferenceError: AjjiAjji is not defined"
I think you are forgetting to add double quotes and the result whould be BindGrid (AjjAjj). try this:
BindGrid("'+msg[i].Name+'")
this should work fine
I think that problem is that the time you are attaching jqGrid to "$("#tblSub"+user)" is not present in DOM.
You should call BindGrid function only after $('#divData').html(table); which is adding table into DOM.
So that jqGrid can properly work.

Categories