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
Related
I have the following code I'm trying to make a simple hit counter with. However, it doesn't work when I run it locally. When I start newHits as blank, it throws the error: Uncaught Error: Reference.set failed: First argument contains undefined in property 'hits.number'.
When I start it at 1, it just doesn't change the value of the hits in the database. Any help is appreciated: I'm new to programming. Thanks so much!
$(document).ready(function(){
var database = firebase.database();
var hits;
var newHits = 1;
var hitsRef = firebase.database().ref('hits');
hitsRef.once('value', function(snapshot){
console.log("hitsRef.once called");
hits = snapshot.val().number;
console.log("hits: "+hits);
newHits = hits+1;
console.log(newHits);
});
hitsRef.set({
number: newHits
});
});
the simple way to do that by using transaction see here
$(document).ready(function(){
var database = firebase.database();
var hitsRef = firebase.database().ref('hits/number');
hitsRef.transaction(function(hits){
console.log("hitsRef.once called");
hits++;
return hits
});
}
This is due to async nature of once(). According to your code, both once() and set() are called for the same value of i at once.
If you want to test it, place your set() within a setTimeout() like,
setTimeout(function(){
hitsRef.set({
number: newHits
});
}, 2000);
You will see that your problem is solved but this is not the correct way.Try this instead,
var i = 1;
hitsRef.once('value', function(snapshot){
console.log("hitsRef.once called");
hits = snapshot.val().number;
console.log("hits: "+hits);
newHits = hits+1;
console.log(newHits);
})
.then( function() { // change starts here
hitsRef.set({
number: newHits
});
});
Your set() method will only be called when once() is done retrieving hits. This works because once() returns a promise and it is thenable.
Read these then() in javascript and promises.
In my application I am loading user posts using the ajax scroll down feature.
The for loop iteration takes too much time, browser freezes until the results are displayed. So I implemented a setTimeout method to fix that, but for some reason the flow doesn't go inside the setTimeout method on debugging.
Also the page is blank, data is not rendered.
success : function(responseJson) {
$("#loadingdata").toggle();
enableScrolling();
if($.isEmptyObject(responseJson)){
$("#noMorePosts").toggle();
disableScrolling();
paginationComplete=true;
}
$.each(responseJson, function (index) {
(function(index) {
setTimeout(function(index) { //the flow doesn't move inside this
var resp_JSON=responseJson[index];
var dateObj=resp_JSON.postCreationTime;
resp_JSON.postCreationTime = moment(dateObj).format("h:mm a, ddd, MMM Do YY");
var timeago = moment(dateObj).fromNow();
resp_JSON.timeago = timeago;
resp_JSON.username=userName;
var post_template = $('#homepostcontainertemplate').html();
Mustache.parse(post_template);
var post_info = Mustache.to_html(post_template, resp_JSON);
$('#homepublisherpostsdiv').append(post_info);
$('div').linkify();
});
})(index);
});
When the flow reaches setTimeout the next code it hits is the jquery lib
Am I doing it right or missing something?
Note: I get the responseJson data from the server fine. Without the setTimeout the data is loaded on the page.
setTimeout takes an argument-less function (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout), so having index as an argument is a little odd. I suspect that index is undefined so responseJson[index] is throwing out of bound exception (as evidenced by console.log(1) showing up as per Niloct's comment). If you change your code to:
$.each(responseJson, function (index) {
setTimeout(function() { // no index in the argument list
var resp_JSON=responseJson[index];
var dateObj=resp_JSON.postCreationTime;
resp_JSON.postCreationTime = moment(dateObj).format("h:mm a, ddd, MMM Do YY");
var timeago = moment(dateObj).fromNow();
resp_JSON.timeago = timeago;
resp_JSON.username=userName;
var post_template = $('#homepostcontainertemplate').html();
Mustache.parse(post_template);
var post_info = Mustache.to_html(post_template, resp_JSON);
$('#homepublisherpostsdiv').append(post_info);
$('div').linkify();
});
});
I suspect it will work.
(edited to take into account jjaulimsing's comment about not needing the encapsulating function.)
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.
Good day everyone,
I am pulling back some data from a database (via a PHP script) using jQuery's .getJSON() method. This is all well and good, the data comes back just fine and as expected. The problem occurs when I try to pass the data to a secondary function, no matter how I try to access the values of that data they come back as undefined. I have a feeling I am overlooking something very simple but after a lot of trial and error I come to SO asking for an extra set of eyes.
Here is a simple example of the JavaScript code.
function fnCheck_Vis(Row, sField, sMode)
{
sField = sField+"_vis";
sTest = Row.sField.val();
alert(sTest); // Comes back as undefined.
}
$(document).ready(function()
{
$("#btnSearch").click(function()
{
$("#divResults").empty();
var ssearch = $("#ssearch").val();
var i = 0;
$.getJSON("get_results.php?keywords=" + ssearch,
function(Data)
{
var iRec = 0;
$.each(Data, function(i, Row)
{
fnCheck_Vis(Row, "slinkpic1", "Int");
var content = Row.slast;
$("#divResults").append(content);
iRec++;
});
alert(iRec + " records retrieved using AJAX.");
});
});
});
The first piece of the fnCheck_Vis() function works fine and "_vis" is appended to the field name, this is proper behavior. No matter how I try to access that member in the dataset (Row) I can not get a value back.
I really appreciate any insight that can be given on this issue.
Thanks,
Nicholas
It looks like you want to access the property of Row whose name is stored in sField, not its actual sField property. Try:
function fnCheck_Vis(Row, sField, sMode)
{
sField = sField + "_vis";
var sTest = Row[sField];
alert(sTest);
}
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.