I did have this code working a few years ago and have recently come back to it, i have a javascript refreshing data on a web page. Im calling the server using json and receiving back what i think is ok.
My python database code, which seems to work fine.
cur = db.execute('select sensor_name, temp from cur_temps ORDER BY sensor_name')
return jsonify(cur.fetchall())
Received Json
[["BoilerRoom",24.94],["Cylinder1",49.94],["Cylinder2",42.38],["Cylinder3",41.88],["Sensor1",85],["SolidFuelFlow",59],["SolidFuelReturn",41.62]]
Im trying to get the number thats associated with Cylinder2 = 42.38
My js code that worked previously is as follows
<script type=text/javascript>
function get_temps() {
$.getJSON("_status",
function (data) {
$('#CylTop').text(data.Cylinder1 + "°")
$('#CylMid').text(data.Cylinder2 + "°")
$('#CylBot').text(data.Cylinder3 + "°")
$('#Solid_flow').text(data.SolidFuelFlow)
$('#Solid_return').text(data.SolidFuelReturn)
$('#BRoom').text(data.BoilerRoom);
console.log(data)
console.log(data.Cylinder1)
}
);
}
setInterval('get_temps()', 5000);
</script>
The console shows the (data) fine in the browser, its when i try and show anything else. ' console.log(data.Cylinder1) ' that shows undefined.
Im a newbie so im assuming some indexing needs to happen as its a array but im a bit lost.
Any guidance will be greatly appreciated.
Many Thanks
C Dabbs
You seem to be accessing the properties in the data as an object. As per the response, it is an array inside an array. So you will have to flatten it before accessing it the way you have it.
function get_temps() {
$.getJSON("_status",
function(data) {
let flattendData = data.reduce(function(acc, item) {
return Object.assign({}, acc, {
[item[0]]: item[1]
});
}, {});
$('#CylTop').text(flattendData.Cylinder1 + "°")
$('#CylMid').text(flattendData.Cylinder2 + "°")
$('#CylBot').text(flattendData.Cylinder3 + "°")
$('#Solid_flow').text(flattendData.SolidFuelFlow)
$('#Solid_return').text(flattendData.SolidFuelReturn)
$('#BRoom').text(flattendData.BoilerRoom);
console.log(flattendData)
console.log(flattendData.Cylinder1)
}
);
}
Related
I am trying to pass a 2D array created in a Javascript file here:
Code.gs
function getPermits()
{
Logger.log('Starting permits');
var permits = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getDataRange().getValues();
Logger.log('Got permits: ' + permits [0][0]);
return permits;
}
And I call that function with a handler in this html file:
<script type="text/javascript">
function onSuccess(numUnread) {
alert('You have ' + numUnread[0][0]
+ ' unread messages in your Gmail inbox.');
document.getElementById("id2").innerHTML = numUnread[0][0];
}
function onFail(numUnread){
alert('Script failed!');
}
google.script.run.withSuccessHandler(onSuccess).getPermits();
google.script.run.withFailureHandler(onFail).getPermits();
</script>
The Logger.log('Got permits: ' + permits[0][0]);
call works perfect no matter what. However, while I can pass a 1D array in this manner and it works fine, passing a 2D array is causing this to fail. Why does this happen? Am I using improper syntax for this?
Thanks in advance
Stringify it as a JSON object, then you can pass just a String, which works fine:
return JSON.stringify(permits);
And on HTML:
function onSuccess(numUnread) {
numUnread = JSON.parse(numUnread);
I have a small angularJs app that needs to check if two people are friends on facebook..
As I following the facebook official api guide: link
from the guide:
/* make the API call */
FB.api(
"/{user-id-a}/friends/{user-id-b}",
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
my code:
(isFriends watching the place in the array to get updated by facebookIsFriends)
$scope.isFriends = function(friend_id){
//$scope.myArray[friend_id]
var tmpStr = 'myArray.' + friend_id;
$scope.facebookIsFriends(friend_id);
var unbindWatcher = $scope.$watch(
tmpStr,
function() {
if(!!$scope.myArray[friend_id]){
unbindWatcher();
//call another function with the result.
}
}
);
}
$scope.facebookIsFriends = function(friend_id){
var urlString = '/' + $scope.user.id + "/friends/" + friend_id;
Facebook.api(urlString, function(response) {
$scope.$apply(function() {
$scope.myArray[friend_id] = response;
});
});
}
i get in return:
data: Array[0]
length: 0
__proto__: Array[0]
summary: Object
total_count: 754
__proto__: Object
note: I do have 754 friends.
important notes:
1.when i try to try this in the graph api explorer I get similar result! (I absolutely sure I checked all of the use data & extended permissions.
2.I'm connected properly to facebook, i did already some queries that worked properly (/me, /me/feed,/{post-id})
3.When I debug the code, I get a proper url string, like:
/10204551896346735/friends/10205037578119229
when I try to put each of these user-is's in the graph-api-explorer i get good results(non-empty user objects)
I already tried million things, like set a long timeout and check if it's updated over time but nothing happens. please help I lost all hope :(
thanks,
Matan
So with the code below I am able to get the information shown below e.g. streamTitle.
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName)), true);
if ($json_array['stream'] != null) {
$currentGame = $json_array['stream']['channel']['game'];
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$viewers = $json_array['stream']['viewers'];
}
But what I want to do is to get what comes after self: e.g.(https://api.twitch.tv/kraken/streams/woohaa666) of an API response like the one below which has a specified game and limit, but I'm not sure how to do so. I tried something similar to the code above $channelurlAPI = $json_array['streams']['self'], but it displays nothing.
https://api.twitch.tv/kraken/streams?game=Diablo+III&limit=1
Im not sure how much this will help you but i was doing work with the twitch API a few months ago I found it very hard but was able to get game searches working and to bring in streams
hope it helps here is the code that i used
//Twitch Streams //Ref: https://github.com/justintv/Twitch-API/blob/master/embedding.md
function getTwitch(title){
$.getJSON("https://api.twitch.tv/kraken/search/streams?q="+title+"&limit=20&type=top&callback=?", function (data) {
var temp = "";
$.each(data.streams.slice(0,5), function (index, item) {
temp = temp + "<a target='frame1' href='http://www.twitch.tv/widgets/live_embed_player.swf?channel=" + item.channel.name + "'><button>"+item.channel.display_name+"</button></a><br />";
});
$("#StreamList").html(temp);
});
}
Here is a sample jsfiddle i build using the original api code that u my use as a jumping of point aswell but the code above is the final code I used
http://jsfiddle.net/F4tsM/10/
You should try
$json_array['_links']['self']
Thanks to #asgoth, I am able to use AngularJS $http service to retrieve stock prices from Yahoo as described here: Cannot read response from AngularJS $resource JSONP get from Yahoo Finance
In the "getHistoricalPrice" function, it puts the price inside an array, which is inside an object. From inside that function, I am able to access the price and write it to console.
The function returns the object to where it is called from. From there, I can successfully write the entire object out to console. However, I cannot access the elements of this object. I tried many different ways, but still cannot access the data in the object. You can see the code at http://jsfiddle.net/curt00/LTazR/2/ or below:
angular.module('app', ['ngResource']);
function AppCtrl($scope, $http, $resource) {
var historical_price = getHistoricalPrice("AAPL", 'start date is hard coded', 'end date is hard coded');
console.log("after calling historical price: ", historical_price); // historical_price is an object and all of the correct data is outputted to console here, but I cannot access its elements directly from Javascript.
for(var key in historical_price) {
console.log("key =",key); // this outputs "key = list"
}
console.log("after calling getHistoricalPrice: ", historical_price.list[0][1]); // Cannot access this as browser console gives error: TypeError: Cannot read property '1' of undefined
console.log("after calling getHistoricalPrice: ", historical_price['list'][0][1]); // Cannot access this as browser console gives error: TypeError: Cannot read property '1' of undefined
console.log("after calling getHistoricalPrice: ", historical_price[0][1]); // Cannot access this as browser console gives error: TypeError: Cannot read property '1' of undefined
function getHistoricalPrice(symbol, start, end) {
var query = 'select * from csv where url=\'http://ichart.yahoo.com/table.csv?s=' + symbol + '&a=' + '11' + '&b=' + '19' + '&c=' + '2012' + '&d=' + '11' + '&e=' + '19' + '&f=' + '2012' + '&g=d&ignore=.csv\'';
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + fixedEncodeURIComponent(query) + '&format=json&callback=JSON_CALLBACK';
var histData = {};
$http.jsonp(url, {timeout: 30000}).success(function(json) {
var list = [];
var result = json.query.results.row;
result.shift(); // remove the header (columns) row
angular.forEach(result, function(row) {
list.push([(new Date(row.col0)).getTime()/1000, parseFloat(row.col4)]);
});
list.sort(function(val1, val2) {
return val1[0] - val2[0];
});
histData.list = list;
console.log('Loaded historical data',histData.list[0][1],', for ' + symbol); // This works and gives the price
});
return histData;
}
var fixedEncodeURIComponent = function(str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
};
}
Any help or suggestions to solve this problem is greatly appreciate!
It's a matter of timing.
In lines 12-14 you are trying to access histData.list before it has been populated. This is because this code is run before the success callback to the $http.jsonp function is executed.
Any code that depends on that callback being completed must be in the callback or in a function called in the callback.
See my answer on https://stackoverflow.com/a/13967709/1916258
A great way to debug the Yahoo api is using the YQL Console: http://developer.yahoo.com/yql/console/
Info about the different posibilities (which stock info) can be found on http://www.gummy-stuff.org/Yahoo-data.htm
Edit: there was still a problem with function fixedEncodeURIComponent. It should encode quotes (") too:
var fixedEncodeURIComponent = function(str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A").replace(/\"/g, "%22");
};
BobS is right, you aren't timing things correctly. Also you declared fixedEncodeURIComponent after you had called it. This was resulting in an immediate error when I loaded up the jsfiddle.
While you were passing the callback through to your function correctly, you weren't actually calling it. I stripped out all the post processing of the json as you have some other errors involving the query and just implemented the callback so you can see it working.
After the request is finished and you're still in the success function you need to add
if(typeof(callback) === "function"){
callback();
}
This calls that function you passed in and runs it. Here is a working jsFiddle of it:
http://jsfiddle.net/LTazR/22/
I also updated a new variable i created call output so you can see it changing.
Thanks to everybody for providing suggestions.
I solved the problem by using AngularJS' $scope variable, such as $scope.symbol[user].price. I created this variable before calling the getHistoricalPrice function and then in that function, after the result is returned from $http.jsonp, I put the value into the $scope variable, as such:
$scope.symbol[user].price = row.col4;
I'm a bit clueless with javascript, so would appreciate pointers with what's (not) happening here.
The following snippet is supposed to populate the data variable with the response (JSON) from a PHP backend. The response variable indeed contains the data (I confirmed with Firebug and a breakpoint):
[Object { identifier=0, value="clothing made in the us"}, Object { identifier=1, value="club penguin trading cards"}, Object { identifier=2, value="cobra quad bikes"}, 22 more...]
However, by the time the return data; line is reached, data contains nothing.
var data = [];
new response.each(function(identifier, item){
this.include({value: identifier, text: item.text});
}, data);
return data;
I'm having difficulty mapping my knowledge of (eg) Perl's foreach loop with what's happening here. I'd appreciate any pointers.
Thanks
Solved
var data = [];
response.each(function(obj) {
this.include({identifier: obj.id, value: obj.descr});
}, data);
return data;
I'll eventually get this JS.