jQuery DataTables duplicates are initially loading - javascript

So, adding on to my question from yesterday: jQuery AJAX call function on timeout
Using the first answer from the post from yesterday, the table does indeed reload without refreshing the whole page. It does so after 30 seconds.
But my problem lies before the first refresh...
The page loads, and the records are duplicated. But after the first refresh and every refresh after (unless I manually refresh using F5), everything is fine. No duplicates.
I'm trying to figure out why there are duplicates and how to remove the duplicates upon the page's initial ready event.
Here is the code, starting with the ready event:
$(document).ready(function()
{
$.ajax({
url:'api/qnams_all.php',
type:"GET",
dataType:"json"
}).done(function(response) {
console.log(response.data);
renderDataTable(response.data)
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
});
Here is the function to load the DataTable:
function renderDataTable(data)
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true
});
// then I add the reload function
setInterval( function () {
$dataTable.ajax.reload();
}, 30000 );
});
As stated above, the setInterval function works like how it should. It's just the initial page load is duplicating all of the records.
Does anyone see why and how to fix it?

I think you've got some duplication going on. You don't need to load the ajax flie and then load it again when you set up the DataTable.
Try replacing all of your code with this:
$(document).ready(function() {
// load and render the data
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true,
// the init function is called when the data table has finished loading/drawing
"init": function() {
// now that the initial data has loaded we can start the timer to do the refresh
setInterval(function() {
$dataTable.ajax.reload();
}, 30000);
}
});
});

Calling clear prevents duplicate rows while loading data into table:
$("#checkResourcesButton").click(function() {
$.post("./get/resources", {
featureName: $('#myvar').val()
}).done(function (data) {
var table = $('#table-output').DataTable();
table.clear();
var json = JSON.parse(data);
for (var row in json) {
var nameVal = json[row].Name;
var emailVal = json[row].emailId;
var roleVal = json[row].role;
var startDateVal = json[row].startDate;
var endDateVal = json[row].endDate;
var toAdd =
{
name: String(nameVal),
emailId: String(emailVal),
role: String(roleVal),
startDate: String(startDateVal),
endDate: String(endDateVal)
};
table.row.add(toAdd);
}
table.draw();
});
});

Related

JQuery & Ajax disable click

I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});

Reload part of the page Jquery

I have a table with a td that updates when i press a button .pauseDocker
When It's paused I'm reloading the page. Surely there's a smarter way to just refresh just part of the page in this case the table.
$(document).on('click','.pauseDocker' ,function(){
var buttonClicked = $(this);
var containerName = $(this).attr('name');
$.ajax({
type: 'post',
url: '/container/pause',
data: {containerName: containerName},
success: function () {
location.reload();
},
error: function() {
}
});
});
You can get the first parameter of the success callback and this will contain data from the response of your server. Use that to retrieve the changed data and update client side accordingly

how to refresh only div with id=calender?

$(document).ready(function() {
$("#client-list").on("change", function() {
var selectedValue = $(this).val();
location.reload();
});
});
how to refresh only div with id='calender', instead of refreshing complete page, onchange dropdown list option? Complete source i have created a fiddle or how to keep slected option in drop down which was selected and refresh rest of the page?
You cannot reload only a part of your page unless you use IFRAMES.
Instead, you'll have to use AJAX. Here is a quick example:
<script>
function refreshCalendar()
{
$.ajax({
type: "GET",
url: 'http://yourdomain/api/whatever',
data: "", // You can send some data to the servers
success: function(data) {
$('#calendar').html(data);
}
});
}
</script>
You can refresh fullCalender as like this.
Put you calendar code in a function LoadCalendar then call it once on document ready and once on change of dropdown.
function LoadCalendar() {
$('#calendar').fullCalendar({
//your options
});
}
$(function(){
LoadCalendar();
$("#client-list").on("change", function() {
var selectedValue = $(this).val();
LoadCalendar();
});
});

jQuery use variable outside function

I'm using jquery.feeds.js to aggregate rss feeds and preprocessing the data received with jsonp.js. The problem is I can't use the variable summarize I've set within the preprocess function outside of it. I did set it as a universal variable though so I don't know what I could be doing wrong. Could it be a problem that I'm running multiple JSON requests?
My code:
$('#feed').feeds({
feeds: {
reuters: 'http://feeds.reuters.com/reuters/businessNews'
},
max: 2,
preprocess: function ( feed ) {
var articleLink = (this.link);
var summarize = '';
$.getJSON({
url: 'https://jsonp.nodejitsu.com/?url=http://clipped.me/algorithm/clippedapi.php?url='+articleLink+'&callback=?',
corsSupport: true,
jsonpSupport: true,
success: function(data){
var summarize = data.summary
}
});
alert(summarize);
this.contentSnippet = summarize
},
entryTemplate: '<h3><!=title!></h3><p><!=contentSnippet!></p><i><!=link!></i>'
});
And a JSFIDDLE
You have a series of errors that are not addressed in the other posts..
the preprocess callback allows for changes in the current object (feed) right before it gets displayed.
Since the getJSON is an ajax call it will get the results too late. And changing the contentSnippet even in the success callback will not fix this.
You use the $.getJSON method as if it was $.ajax. So you pass it wrong arguments. Just use $.ajax for your syntax
finally to fix the first issue, you need to alter your template a bit so you can find the relevant parts later on (when the ajax requests complete) and use the onComplete callback instead (of the feeds plugin)
All changes together give
$('#feed').feeds({
feeds: {
reuters: 'http://feeds.reuters.com/reuters/businessNews'
},
max: 2,
onComplete: function(entries){ // use onComplete which runs after the normal feed is displayed
var $this = $(this);
entries.forEach(function(entry){
var $self = $this.find('.entry[data-link="'+entry.link+'"]');
$.ajax({
url:'https://jsonp.nodejitsu.com/?url=http://clipped.me/algorithm/clippedapi.php?url='+entry.link,
corsSupport: true,
jsonpSupport: true,
success: function(data){
// add the results to the rendered page
$self.find('.snippet').html( data.summary );
}
});
});
}, // change the template for easier access through jquery
entryTemplate: '<div class="entry" data-link="<!=link!>"><h3><!=title!></h3><p class="snippet"><!=contentSnippet!></p><i><!=link!></i></div>'
});
Demo at http://jsfiddle.net/gaby/pc7s2bmr/1/
I think you mean this
$('#feed').feeds({
feeds: {
reuters: 'http://feeds.reuters.com/reuters/businessNews'
},
max: 2,
preprocess: function ( feed ) {
var articleLink = (this.link);
var summarize = '';
var that = this;
$.getJSON({
url: 'https://jsonp.nodejitsu.com/?url=http://clipped.me/algorithm/clippedapi.php?url='+articleLink+'&callback=?',
corsSupport: true,
jsonpSupport: true,
success: function(data){
that.contentSnippet = data.summary
}
});
},
entryTemplate: '<h3><!=title!></h3><p><!=contentSnippet!></p><i><!=link!></i>'
});
Mathletics is correct. Do this...
$('#feed').feeds({
feeds: {
reuters: 'http://feeds.reuters.com/reuters/businessNews'
},
max: 2,
preprocess: function ( feed ) {
var articleLink = (this.link);
var summarize = '';
var _this = this;
$.getJSON({
url: 'https://jsonp.nodejitsu.com/?url=http://clipped.me/algorithm/clippedapi.php?url='+articleLink+'&callback=?',
corsSupport: true,
jsonpSupport: true,
success: function(data){
_this.contentSnippet = data.summary
}
});
alert(summarize);
},
entryTemplate: '<h3><!=title!></h3><p><!=contentSnippet!></p><i><!=link!></i>'
});

Delete table row with JQuery animation in Firefox

I have an HTML table which uses jQuery DataTables (https://datatables.net/). The rows are rendered with html links to delete a row. I have used the following code to handle the click event of link, delete the row on the server and then animate deletion of the row on the front end.
$(document).on("click", ".delete-operation", function (e) {
e.preventDefault();
var oTable = $('#alloperations').dataTable();
var operationId = $(this).data('id');
// Get the parent table row and mark it as having been selected
// due to the fact rowindex does not work in order in datatables
var tableRow = $(e.toElement).parents('tr').addClass('row_selected');
bootbox.confirm("Are you sure?", function (answer) {
if (answer) {
// send request to delete operation with given id.
$.ajax({
type: 'delete',
url: "/operations/" + operationId,
success: function () {
var anSelected = fnGetSelected(oTable);
//Get all the row cells and animate a deletion
tableRow.children().animate({ backgroundColor: "red", color: "black" }, 300, function() {
tableRow.fadeOut(2000, function() {
oTable.fnDeleteRow(anSelected[0]);
});
});
},
error: function(result) {
$("#messageContainer").html(result.responseJSON.ResponseView);
}
});
return true;
}
else {
// User clicked cancel
return true;
}
});
});
QUESTION: This works perfectly in Chrome but does not work at all in Firefox, does anyone know how I would get it to work in Firefox as well?
You should use the cross browser property 'target' of event object:
var tableRow = $(e.target).parents('tr').addClass('row_selected');

Categories

Resources