JSON BTC/LTC ticker is not working anymore - javascript

I have been using this JSON ticker for the last month. It has been working like a charm, but today it stopped working; maybe anyone knows what could have gone wrong here?
$(function () {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh, 10000);
var turl = 'https://btc-e.com/api/2/ltc_btc/ticker';
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22' + encodeURIComponent(turl) + '%22&format=json', function (data) {
jQuery('#ticker').html(data['query'].results.ticker.last);
jQuery('#ticker').append(' BTC');
});
}
http://jsfiddle.net/marcetin/9FHp3/4/
Here is the same example but with Cryptsy API and works well:
http://jsfiddle.net/marcetin/P2t9R/2/

I checked out https://btc-e.com/api/2/ltc_btc/ticker and got JSON back, so the issue is not with that site.
I checked out your code, and aside from being a little dirty, there was nothing that would keep it from pulling that service.
So, the issue seems to be at Yahoo's side. Purhaps that API is no longer available through Yahoo.
I have have cleaned up (and commented) your code:http://jsfiddle.net/9FHp3/27/
// Function for pulling JSON
function startRefresh() {
// This is the API URL
var turl = 'https://btc-e.com/api/2/ltc_btc/ticker';
// This sends the API URL through Yahoo?
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22' + encodeURIComponent(turl) + '%22&format=json', function (data) {
// Writes to the page
$('#ticker').html(data['query'].results.ticker.last+' BTC');
});
}
// Do the initial pull
startRefresh();
// Refresh every 10000
setInterval(startRefresh, 10000);
However, you should really be pulling REST APIs from a server-side code such as PHP. Unless they are available in JSONP or CORS they are not really intended for cross-domain client-side script.
I hope this helps!

Related

Only run a function once in JavaScript? [duplicate]

I'm using a page loader on the front page of my website, I'd like it to run only the first time someone visits my website, so later on since the page will be cached it'll execture faster and thus I won't need the loader the next times he visits.
I thought using storing a signal to caches/cookies to do so, but I have no idea how ?
here is the loader javascript :
function myFunction() {
var myVar = setTimeout(showPage, 1000);
}
function showPage() {
$("#loader_sec").css("display","none");
$("#bodyloader").css("display","block");
}
myFunction();
<div id="loader_sec">
...
</div>
How should I configure caches/cookies to launch this code only the first time someone visits ? If there are better ways to do so please suggest.
Try this:
function myFunction() {
var myVar = setTimeout(showPage, 1000);
}
function showPage() {
$("#loader_sec").css("display","none");
$("#bodyloader").css("display","block");
}
if(!localStorage.getItem("visited")){
myFunction();
localStorage.setItem("visited",true);
}
<div id="loader_sec">
...
</div>
Try with Session/local storage. Like this -
$(window).load(function () {
$(function () {
if (!sessionStorage.getItem("runOnce")) {
// Your code goes here....
sessionStorage.setItem("runOnce", true);
}
});
});
You'll need to persist some data on the user's device in order to know that they have visited your site before. You would do this via local storage or cookies.
Here is a simple library you can use to read/write cookies: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework
You could write a value to a cookie when the user has been shown the page loader. A check for this value when the page loads will let you know if the loader has been displayed previously or not and inform your decision about whether it should be displayed this time.
I would do the logic in a caching/data access layer. You can use https://github.com/kriskowal/q for executing functions as a callback when another function completes.
Then you can do
getData(key)
.then(function () {
hideLoader(); // Function for your show/hide logic
});
or something of the sort.
getData would look something like:
var getData = function (key) {
var deferred = Q.defer();
if (cache[key]) {
deferred.resolve(cache[key]);
} else {
//Data request logic that returns 'data'
deferred.resolve(data);
}
return deferred.promise;
};
This way you're not guessing how long your requests are going to take and you're not forcing a second long load time on your user because the page will load as soon as your data has been retrieved.
By the way, the cache here is just a key/value store. Aka var cache = {};

Weird (caching) issue with Express/Node

I've built an angular/express/node app that runs in google cloud which currently uses a JSON file that serves as a data source for my application. For some reason, (and this only happens in the cloud) when saving data through an ajax call and writing it to the json file, everything seems to work fine. However, when refreshing the page, the server (sometimes!) sends me the version before the edit. I can't tell whether this is an Express-related, Node-related or even Angular-related problem, but what I know for sure is that I'm checking the JSON that comes in the response from the server, and it really is sometimes the modified version, sometimes not, so it most probably isn't angular cache-related.
The GET:
router.get('/concerts', function (request, response) {
delete require.cache[require.resolve('../database/data.json')];
var db = require('../database/data.json');
response.send(db.concerts);
});
The POST:
router.post('/concerts/save', function (request, response) {
delete require.cache[require.resolve('../database/data.json')];
var db = require('../database/data.json');
var concert = request.body;
console.log('Received concert id ' + concert.id + ' for saving.');
if (concert.id != 0) {
var indexOfItemToSave = db.concerts.map(function (e) {
return e.id;
}).indexOf(concert.id);
if (indexOfItemToSave == -1) {
console.log('Couldn\'t find concert with id ' + concert.id + 'in database!');
response.sendStatus(404);
return;
}
db.concerts[indexOfItemToSave] = concert;
}
else if (concert.id == 0) {
concert.id = db.concerts[db.concerts.length - 1].id + 1;
console.log('Concert id was 0, adding it with id ' + concert.id + '.');
db.concerts.push(concert);
}
console.log("Added stuff to temporary db");
var error = commit(db);
if (error)
response.send(error);
else
response.status(200).send(concert.id + '');
});
This probably doesn't say much, so if someone is interested in helping, you can see the issue live here. If you click on modify for the first concert and change the programme to something like asd and then save, everything looks fine. But if you try to refresh the page a few times (usually even up to 6-7 tries are needed) the old, unchanged programme is shown. Any clue or advice greatly appreciated, thanks.
To solve: Do not use local files to store data in cloud! This is what databases are for!
What was actually the problem?
The problem was caused by the fact that the App Engine had 2 VM instances running for my application. This caused the POST request to be sent to one instance, it did its job, saved the data by modifying its local JSON file, and returned a 200. However, after a few refreshes, the load balancing causes the GET to arrive at the other machine, which has its individual source code, including the initial, unmodified JSON. I am now using a MongoDB instance, and everything seems to be solved. Hopefully this discourages people who attempt to do the same thing I did.

Why this polling stops working after idling for some time?

I am using AngularJS to constantly poll for new data through HTTP POST. An alert will be sent when new data is received. The code which is inside a controller looks something like this;
var poll = function() {
$http.get('phones.json').success(
function(data)
{
new_val = data.val;
if ( (new_val!== old_val) )
{
$window.alert("AlertEvent");
}
old_data = new_val;
$timeout(poll, 500);
}
);
};
poll();
This code works when the html page is refreshed. Working means when phones.json is changed, an alert will appear. However, if I leave the page on for, say 30 minutes, and come back later, it stops working. I have to refresh the page to get it working again.
What else did I miss out? What did I do wrong? Could it due to some caching mechanism?
Thank you very much.
EDIT: I found the cause. It is indeed due to the browser reading from cache. I can see this using Chrome Developer tools. How can this caching be disabled for this html page only?
You may be able to bust the cache by doing something like this:
$http.get('phones.json?v=' + Date.now())
Depending on how your back-end is set-up you may need to adjust it to accept that.

Blockchain API, AJAX request has stopped working, CORS issues?

I've been playing with the multiple address look up API from blockchain info (documented here https://blockchain.info/api/blockchain_api), I had my code working earlier in the day but bizzarely it's stopped.
The purpose of it is to eventually write a little JQuery library which will search the DOM for bitcoin addresses as data attributes and then insert the final balance into that element creating a polling mechanism to keep the page updated as well.
The original problem I ran into earlier while developing it was because it's a CORS ajax request but later I adjusted the query per the blockchain info API documents and I added cors=true it then seemed to work fine but now it doesn't seem to want to work at all again. I don't get how changing computers would effect this kind of request.
Here's my code on JSFiddle, http://jsfiddle.net/SlyFoxy12/9mr7L/7/
My primary code is:
(function ($) {
var methods = {
init: function(data, options) {
//put your init logic here.
},
query_addresses: function(addresses) {
var addresses_implode = addresses.join("|");
$.getJSON("http://blockchain.info/multiaddr?cors=true&active="+addresses_implode, function( data ) {
$.each( data.addresses, function( index ) {
$('#output').append(" "+data.addresses[index].final_balance);
});
});
}
};
$.fn.bitstrap = function () {
var addresses = new Array();
$('[data-xbt-address]').each(function () {
$(this).text($(this).data('xbtAddress'));
addresses.push($(this).data('xbtAddress'));
});
methods.query_addresses(addresses);
}
}(jQuery));
$().ready(function() {
$().bitstrap();
});
Ok, turns out it's an issue with Chrome some how, I've tried it in safari and it works again, it must have been a different version of Chrome on the other computer I used.
There seems to be more info about it here https://code.google.com/p/chromium/issues/detail?id=104920

how to load google client.js dynamically

this is my first time to post here on stackoverflow.
My problem is simple (I think). I am tasked to allow users to sign up using either Facebook, Google Plus, LinkedIn and Twitter. Now, what I want to do is when the user clicks the Social Network button, it will redirect them to the registration page with a flag that determines which social network they want to use. No problem here.
I want to load each API dynamically depending on which social network they choose.
I have a problem when loading the Google JS API, dynamically. The sample found in here loads client.js in a straightforward manner. I have no problems if I follow the sample code. But I want to load it dynamically.
I tried using $.ajax, $.getScript and even tried adding the script to the page just like how you call Google Analytics asynchronously. None of the above worked. My call back function is NOT called all the time. Also, if i call the setApiKey from the call back function of $.ajax and $.getScript, the gapi.client is NULL. I don't know what to do next.
Codes that did not work:
(function () {
var gpjs = document.createElement('script'); gpjs.type = 'text/javascript'; gpjs.async = false;
gpjs.src = 'https://apis.google.com/js/client.js?onload=onClientLoadHandler';
var sgp = document.getElementsByTagName('script')[0]; sgp.parentNode.insertBefore(gpjs, sgp);})();
Using $.getScript
$.getScript("https://apis.google.com/js/client.js?onload=onClientLoadHandler", function () {
console.log("GP JS file loaded.");
SetKeyCheckAuthority();});
Using $.ajax
$(document).ready(function () {
$.ajax({
url: "https://apis.google.com/js/client.js?onload=onClientLoad",
dataType: "script",
success: function () {
console.log("GP load successful");
SetKeyCheckAuthority();
},
error: function () { console.log("GP load failed"); },
complete: function () { console.log("GP load complete"); }
});});
May I know what is the proper way of calling this js file dynamically? Any help would be appreciated. Thank you.
Ok, I just thought of a solution but i think it's a bad one. Please let me know what you think of it.
i used $.getScript to load the js file
$.getScript("https://apis.google.com/js/client.js?onload=onClientLoadHandler", function () {
console.log("GP JS file loaded.");
SetKeyCheckAuthority();});
and then on my SetKeyCheckAuthority function i placed a condition to call itself after 1 second when gapi.client is null.
function SetKeyCheckAuthority() {
if(null == gapi.client) {
window.setTimeout(SetKeyCheckAuthority,1000);
return;
}
//set API key and check for authorization here }

Categories

Resources