I'm going through an issue with Jquery DataTables.
I have several DataTables, but I want to assign only one of them to another variable and use it.
Small code for exemple below:
var time = "morning";
var helloTable;
var goodMorningTable = $('#goodMorning').DataTable({
...
});
var goodAfternoonTable = $('#goodAfternoon').DataTable({
...
});
var goodEveningTable = $('#goodEvening').DataTable({
...
});
function sayHello(time) {
switch(time) {
case "morning":
helloTable = goodMorningTable;
break;
case "afternoon":
helloTable = goodAfternoonTable;
break;
case "evening":
helloTable = goodEveningTable;
break;
}
helloTable.draw(); // And do more things with it
}
$('#btnAfternoon').on('click', function () {
sayHello("afternoon");
});
My code is more complicated than that but follows more or less the same structure. My DataTables data come from the server (AJAX).
In debug mode I can see that the draw() instruction is executed but nothing happens. I see that nothing happens because there is no "loading" time.
Please tell me if it's not clear enough.
What can you suggest to make it work?
Thanks in advance.
Related
I'm aware that the immediate response is going to be to use promises for the following problem. However, I've looked at every example I can and nothing seems to be readable to me. Most is done through HTML examples, which I don't understand. Similar posts here have a plethora of arguments on which syntax is appropriate which furthers the confusion. So, please show me how I might use a promise to do the following or if another solution is better.
I'd like for a function to check if the cache is available, and if not, it will reinitialize the cache:
function valData(){
if (arrOfNames || arrOfRanges == null){
initializeGame();
Logger.log('Game Initialized')
}
else {
Logger.log('Data Available')
}
};
I'm aware this is likely sloppy, but stay with me
This function works as intended, as does the following:
function reqVal(valname,x){
if (x == 0){
var nameArr = convToString(arrOfNames);
var valIndex = nameArr.indexOf("" + valname)
return arrOfRanges[valIndex];
}
else {
var nameArr = convToString(arrOfNames);
var valIndex = nameArr.indexOf("" + valname)
return valIndex;
}
};
Again, very very sloppy but Ill clean things up once I can make them function
Both of these scripts work fine on their own and return what I need. But if I have a third script:
function test(){
valData();
var valNum = reqVal('curHP', 0);
var valIndex = reqVal('curHP',1)
var newNum = valNum - 5;
Logger.log(valNum)
Logger.log(newNum)
Logger.log(valIndex)
};
The reqVal() function fails due to the asynchronous nature of GAS and the Cache having expired, but the valData() function succeeds and produces the needed array. So, I know I need to add a promise in valData() that the reqVal() function can read from but have no idea how to format that as examples I've seen have been very unclear.
First of all, I'm using JQuery. Take a look:
$(document).ready(function() {
var btcusd = 600;
function getRate() {
$.get("rate.php", function(data) {
var btcArr = JSON.parse(data, true);
btcusd = btcArr["last"];
//This will give me the correct value
console.log(btcusd);
});
}
setInterval(function() {
//This will say 600 every time
console.log(btcusd);
//Update rate for next loop
getRate();
}, 3000);
});
Chrome console gives me the 600 every 3 seconds. If I do this manually in the chrome live console, I will get a real value, like 595.32.
Why does this not work like intended?
Thanks for help.
I think #Tobbe is quite on point here. One thing you can do to confirm, is to add something like console.log( btcArr ) and that should show you whether you're getting anything back.
I set up a not too different demo that should that once the ajax callback successfully updates the value, it never goes back to 600, showing that indeed the value does get changed in the callback and the new value is available outside the ajax callback.
The ajax code I used is:
function getRate() {
var gafa = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=100&q=";
var url = gafa + encodeURI('http://news.yahoo.com/rss/sports/')+"&callback=?";
$.getJSON(url, function(data) {
//var btcArr = JSON.parse(data, true);
var xData = data.responseData.feed.entries
//btcusd = btcArr["last"];
btcusd = xData.length;;
//This will give me the correct value
console.log(btcusd);
});
}
The rest of the code is yours: WORKING JSFIDDLE DEMO
I'm having trouble getting a nested AJAX call to work properly. All I want is to have the inner AJAX call executed if and after the outer AJAX call completed successfully.
var diningHours = $("#diningHours");
var facStaffDiningData = $("#facStaffDiningData");
var diningCommonsData = $("#diningCommonsData");
if($.trim(diningHours.html()).length == 0) {
var season;
//This call executes fine (tested it with console logging)
$.get("data/dining-hours.php", {summer: "check"}, function(seasonData, seasonStatus) {
if(seasonStatus == "success") {
season = seasonData;
//This is the call that isn't being executed
$.get("data/dining-hours.php", function(hoursData, hoursStatus) {
if(hoursStatus == "success") {
var hours = $(hoursData).find("hours dining");
var html = hoursFeed(hours, season);
diningHours.append(html).collapsibleset("refresh");
}
});
}
});
}
Am I doing something wrong?
I'd try something like this:
var diningHours = $("#diningHours"),
facStaffDiningData = $("#facStaffDiningData"),
diningCommonsData = $("#diningCommonsData");
if(!$.trim(diningHours.html()).length) {
var XHR = $.get("data/dining-hours.php", {summer: "check"});
XHR.success(function(seasonData) {
var season = seasonData,
XHR2 = $.get("data/dining-hours.php");
XHR2.success(function(hoursData) {
var hours = $(hoursData).find("hours dining"),
html = hoursFeed(hours, season);
diningHours.append(html).collapsibleset("refresh");
});
});
}
The question is, what exactly is hours dining, and how do you expect the find() function to find it ?
I think seasonStatus is redundant, because the callback will be executed on success.
This should works
var season;
//This call executes fine (tested it with console logging)
$.get("data/dining-hours.php", {summer: "check"}, function(season, seasonStatus) {
console.log('CB1',season);
$.get("data/dining-hours.php", function(hoursData) {
console.log('CB2',hoursData);
var hours = $(hoursData).find("hours dining");
var html = hoursFeed(hours, season);
diningHours.append(html).collapsibleset("refresh");
});
}
});
Digging deeper into the issue I found the true source of my problem. The XML document had a bunch of encoding errors (there were things like reserved and copyright symbols in with the data). Removing these and replacing them with the correct entities fixed the problem. My original code that I thought was the issue now works perfectly fine.
yeah, so can i do that?
i have a program already written that has two functions.. and one is recursive..
so i want to know how can i execute just one line of code at a time by pressing a button..
i hope it's possible
and also i'm doing this in a web page
this is my script.. it has no importance but just for you to make an idea..
READ THIS... i don't want to debug it with firebug or whatever... i want to make this myself inside my program... i want to make the code execute 1 line at a time when i press a button..so basically im building my own debugger.. the graphical part is already done.. i only need to know how to do this..
function nod(){
var info;
var st;
var dr;
}
function help(){
var rad;
}
var h = new help();
h.rad = new nod();
h.rad = null;
function create(h,x)
{
if(h.rad==null)
{
h.rad = new nod();
h.rad.info = x ;
h.rad.st = h.rad.dr = null;
}
else{
if(x < h.rad.info){
var h1;
h1 = new help();
h1.rad = h.rad.st;
create(h1,x);
h.rad.st = h1.rad;
}
else{
var h2;
h2 = new help();
h2.rad = h.rad.dr;
create(h2,x);
h.rad.dr = h2.rad;
}
}
}
function read(h)
{
var input = [0,10,2,1,8,9,4,5,3,6,20,11,30,21,31,22,23,
];
var i;
for(i=1;i<=16;i++)
{
create(h,input[i]);
}
}
read(h);
Open your site in Chrome and use the integrated script debugger to execute the script step by step after a breakpoint you set.
But have at least a quick look at the whole box of tools I linked too to ensure you know what you can expect and use the best tool for your need.
I grabbed a bit of code to do some paging with jQuery, via Luca Matteis here
Paging Through Records Using jQuery
I've made some edits to the paging script so that I can use the same code to provide paging of different content in different locations on the same site.
For the most part, I think it works, except that I get a jsonObj is undefined error in firebug.
When I use alert(jsonObj.toSource()), I am shown the variables that I am trying to populate, but at the same time, the script dies because of the error.
I can't figure out why I am getting this conflict of 'undefined' and yet I can easily out put the 'undefined' values in an alert. I can even say alert(jsonObj.name), and it will give me that value, but still launch an jsonObj is undefined error.
Here's the code I'm using
var pagedContent = {
data: null
,holder: null
,currentIndex : 0
,init: function(data, holder) {
this.data = data;
this.holder=holder;
this.show(0); // show last
}
,show: function(index) {
var jsonObj = this.data[index];
if(!jsonObj) {
return;
}
var holdSubset='';
for(i=0;i<=4; i++){
jsonObj=this.data[index+i];
this.currentIndex = index;
if(this.holder=='div#firstList'){
var returnedId = jsonObj.id;
var returnedName = jsonObj.name;
var calcScore=this.data[index+i].score/this.data[0].score*100;
var resultInput="<div ' id='"+returnedId+"'><div class='name'>"+returnedName+"</div><div class='score'><div style='width:"+calcScore+"%;'></div></div>";
}
if(this.holder=='div#secondList'){
var name=jsonObj.name;
var city=jsonObj.city;
var region=jsonObj.state;
var resultInput='<li><div>'+name+'</div<div>'+city+'</div><div>'+region+'</div></li>';
}
holdSubset= holdSubset+resultInput;
}
jQuery(this.holder).html('<br/>'+holdSubset);
if(index!=0){
var previous = jQuery("<a>").attr("href","#").click(this.previousHandler).text("< previous");
jQuery(this.holder).append(previous);
}
if(index+i<this.data.length){
var next = jQuery("<a style='float:right;'>").attr("href","#").click(this.nextHandler).text("next >");
jQuery(this.holder).append(next);
}
}
,nextHandler: function() {
pagedContent.show(pagedContent.currentIndex + 5);
return false;
}
,previousHandler: function() {
pagedContent.show(pagedContent.currentIndex - 5);
return false
}
};
I call the function like this
pagedContent.init(json.users.locations, 'div#secondList');
The json looks like this
{"locations" : [ {"id":"21319","name":"Naugatuck American Legion","city":"Ansonia","region":"Connecticut"},{"id":"26614","name":"Studio B789","city":"Acton","region":"Maine"},{"id":"26674","name":"Deering Grange Hall","city":"Bailey Island","region":"Maine"},{"id":"27554","name":"Accu Billiards","city":"Acushnet","region":"Massachusetts"}]}
I may have found the problem with your code:
for(i=0;i<=4; i++){
jsonObj=this.data[index+i];
(...)
When you call show(0) you set index to 0. You expect a fixed number of items in the array (5 in the range [0..4]) but there are only 4 locations in your data.
If you are using console.log to trace the problems in firebug you might find that it is a problem with firebug. Try just running console.log on it's own.
If it is a problem with firebug try updating it. There are some development versions around which might fix the problem.
I had a similar problem and fixed it by doing the above.