I making my own real time youtube subscriber counter but refresh time is to high and when I change refresh time it not happening. Can someone tell me what I am doing wrong?
<html>
<head>
<link rel="stylesheet" href="odometer-theme-default.css"/>
<script src="odometer.js"></script>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<style>
.odometer {
font-size:100px;
}
#ytName {
font-size: 52px;
font-family:Arial;
}
</style>
</head>
<script type="text/javascript">
$(document).ready( function() {
var chanName = "";
loadChannel("UCPKqr9qSEXi6r03B18wRj6g");
function loadChannel(name) {
chanName = name;
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+name+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url, function(data) {
$("#odometer").html(data.items[0].statistics.subscriberCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+chanName+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url1, function(data) {
$('#ytName').html(data.items[0].snippet.title);
$('#ytLink').html('Link');
});
}
setInterval( function() {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+chanName+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url, function(data) {
$("#odometer").html(data.items[0].statistics.subscriberCount);
}, 1000);
});
});
</script>
<body background = "bg.jpg">
<center>
<div id="ytName"></div>
<div id="ytLink"></div>
<div id="odometer" class="odometer"></div>
</center>
</body>
Maybe javascript should be written differently?
if you write the new time in milliseconds, the response is a bit
setInterval( function() {
// update code is here
}, 1000)
Related
I have written a small JavaScript function which will perform an Ajax request every x amount of seconds.
I was hoping some of you could give it a look over and give me any pointers on redundant code or bad practice.
The idea of the function is to:
1) Allow for polling to be initiated
2) Once initiated, poll once every x seconds and perform an ajax request.
3) Stop polling once disablePolling() is run.
Here is the code:
requester.js
function Request() {
this.poll = false;
this.activatePoll = function () {
this.poll = true;
this.runPoll();
};
this.disablePoll = function () {
this.poll = false;
};
this.runPoll = function () {
var self = this;
var poll = setTimeout(function () {
$.ajax({
url: './request.php',
success: function (response) {
console.log(response);
},
dataType: "json",
complete: function () {
if (self.poll == false) {
clearTimeout(poll);
} else {
self.runPoll();
}
}
})
}, 1000);
};
}
For anyone else which wants to run the code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Requester</title>
</head>
<body>
<h1>Requester</h1>
<div id="requester">
<input type="button" onclick="$request.test();" value="test">
<input type="button" onclick="$request.activatePoll();" value="poll">
<input type="button" onclick="$request.disablePoll();" value="turn off poll">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="js/request.js"></script>
<script>
$(document).ready(function () {
$request = new Request();
});
</script>
</html>
request.php
<?php
echo json_encode($time());
?>
Thank you.
I'm getting "Uncaught ReferenceError: refreshAgonas is not defined "
The players div is filled correctly. Do I need some kind of special define with the JS functions in the JS file?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-draw.js"></script>
<h2>Game</h2>
<div class="agonas">
<script>
setInterval(refreshAgonas, 5000);
var inRequesG = false;
</script>
</div>
<h2>Players</h2>
<div class="players">
<script>
setInterval(refreshPlayers, 5000);
var inRequest = false;
</script>
</div>
</html>
jquery-draw.js
function refreshPlayers() {
if (inRequest) {
return false;
}
inRequest = true;
var load = $.get('playersdata.php');
$(".players").html('Refreshing');
load.error(function () {
console.log("Mlkia kaneis");
$(".players").html('failed to load');
// do something here if request failed
});
load.success(function (res) {
console.log("Success");
$(".players").html('<table border="1"><tr><th>ID</th><th>Name</th><th>Email</th><th>League</th><th>Sex</th><th>Birthday</th></tr>' + res + '</table>');
});
load.done(function () {
console.log("Completed");
inRequest = false;
});
}
function refreshAgonas() {
if (inRequestG) {
return false;
}
inRequestG = true;
var load = $.get('playersdata.php');
$(".agonas").html('Refreshing');
load.error(function () {
console.log("Mlkia kaneis");
$(".agonas").html('failed to load');
// do something here if request failed
});
load.success(function (res) {
console.log("Success");
$(".agonas").html('<table border="1"><tr><th>ID</th><th>Name</th><th>Email</th><th>League</th><th>Sex</th><th>Birthday</th></tr>' + res + '</table>');
});
load.done(function () {
console.log("Completed");
inRequestG = false;
});
}
Now I saw the problem:
Replace
var inRequesG = false;
With
var inRequestG = false;
You forgot the "t"
Try defining the functions like this:
var refreshPlayers = function () {};
var refreshAgonas = function () {};
Try this and respond with the results.
EDIT: didn't mean to include the parenthesis.
Try replacing:
setInterval( refreshAgonas, 5000);
With this:
setInterval(function(){ refreshAgonas()}, 5000);
I'm using JStree to display an XML file, and after displaying it the user can create, rename, or delete some nodes, and sor sure these changes appear only on the displayed xml and not reflected on the original file, I want to know how to reflect this changes to the original XML fie back after clicking like a submit button, or at least how to get the data changed.
Update
The code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>menu-editor</title>
<script type="text/javascript" src="src/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="src/jstree/jquery.cookie.js"></script>
<script type="text/javascript" src="src/jstree/jquery.hotkeys.js"></script>
<script type="text/javascript" src="src/jstree/jquery.jstree.js"></script>
<link href="themes/!style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="src/jstree/!script.js"></script>
<script type="text/javascript" src="src/UIMTreeProcessor.js"></script>
<style type="text/css">
.
.
.
//css stuff
</style>
</head>
<body>
<div id="dummy"></div>
<div id="mylist">
<li id='root'><a href='#'>Root node</a><ul><li><a href='#'>Child node</a></li></ul></li>
</div>
<div id="submit" class="submit_btn">Submit</div>
</body>
<script type="text/javascript" class="source below">
var _url = "cafe.xml";
var _uimTree = null;
$(function () {
getTopContent();
});
getTopContent = function(){
$.ajax({
type: "GET",
url: _url,
dataType:"xml",
cache: false,
beforeSend:function(){
//do something before send
},
success: function(data){
processXML(data);
},
error:function(e){
alert("Error: "+e);
}
});
}
processXML = function(root){
_uimTree = new UIMTreeProcessor(root, $("#mylist"));
_uimTree.doProcess();
}
$('#submit').on('click',function(){
//alert the entire XML after edits via (getXML)
});
</script>
And the UIMtreeprocessor Library code
function UIMTreeProcessor(data, treeEl) {
this.data = data;
this.treeEl = treeEl;
}
UIMTreeProcessor.prototype.initTree = function(data){
this.treeEl.jstree({
"json_data" : {
"data":data,
"progressive_render":"true"
},
"plugins" : ["themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys","contextmenu"],
"core":{"animation":0}
});
}
UIMTreeProcessor.prototype.doProcess = function(){
//Find root:
var _root = $(this.data).children(':first-child');
var _a_feed = new Array();
this.vsTraverse($(_root), _a_feed);
var _treedata = [{"data":_root[0].nodeName,"children":_a_feed, "state":"open"}];
this.initTree(_treedata);
}
UIMTreeProcessor.prototype.vsTraverse = function(node, arr){
var _ch = $(node).children();
for(var i=0; i<_ch.length; i++){
var _vsArr = new Array();
this.vsTraverse(_ch[i], _vsArr);
var _a_att = this.vsTraverseAtt(_ch[i]);
if(null!=_a_att){
_vsArr.push([{"data":"Attributes "+"["+_ch[i].nodeName+"]","children":_a_att, attr : { "class" : "uim_attr"}}]);
}
if(null!=_ch[i].firstChild && 3==_ch[i].firstChild.nodeType){
arr.push([{"data":_ch[i].nodeName + ": " + _ch[i].firstChild.textContent,"children":_vsArr, "state":"open"}]);
}else{
arr.push([{"data":_ch[i].nodeName,"children":_vsArr, "state":"open"}]);
}
}
}
UIMTreeProcessor.prototype.vsTraverseAtt = function(node){
var _a_atts = null;
if(null!=node.attributes && node.attributes.length > 0){
_a_atts = new Array();
for(var i=0; i<node.attributes.length; i++){
_a_atts.push(node.attributes[i].nodeName + ":" + node.attributes[i].nodeValue);
}
}
return _a_atts;
}
Edit: I was really wrong in my original answer.
There is a get_xml method in the xml_data plugin, which is supposed to do what you describe. I have not tested it myself, but if it's anything like json_data.getJSON, the output will contain all kinds of JStree metadata which you will not want to put back into your XML.
My client puts our below JS code in his website in the <head> and is complaining our tags are not firing. Below is the sample code from client:
<html>
<head>
<script type="text/javascript">
function create() {
try {
var baseURL = "https://serv2ssl.vizury.com/analyze/analyze.php?account_id=VIZVRM1125";
var analyze = document.createElement("iframe");
analyze.src = baseURL;
var node = document.getElementsByTagName("script")[0];
node.parentNode.insertBefore(analyze, node);
} catch (i) {
}
}
var existing = window.onload;
window.onload = function() {
if (existing) {
existing();
}
create();
}
</script>
</head>
<body onload="javascript:clientfunction();">
<script type="text/javascript">
function clientfunction()
{
//client code is replcad here
document.write("Hello testing");
}
</script>
</body>
</html>
On page Load clientfunction() is calling, our create() function is not firing.
Please can anybody help me why our tags are not firing and what is the alternative solution for this issue?
copy paste and check running following
<html>
<head>
<script type="text/javascript">
function create() {
alert("Gdfg");
try {
var baseURL = "https://serv2ssl.vizury.com/analyze/analyze.php?account_id=VIZVRM1125";
var analyze = document.createElement("iframe");
analyze.src = baseURL;
var node = document.getElementsByTagName("script")[0];
node.parentNode.insertBefore(analyze, node);
} catch (i) {
}
}
window.onload=create;
window.onload=clientfunction;
</script>
</head>
<body onload="clientfunction(); create()">
<script type="text/javascript">
function clientfunction()
{
alert("fdsfsdf");
//client code is replcad here
document.write("Hello testing");
}
</script>
</body>
</html>
what's wrong here?
OPTIONS https://twitter.com/oauth/request_token 401 (Unauthorized)
jsOAuth-1.3.4.js:483 XMLHttpRequest cannot load
https://twitter.com/oauth/request_token. Origin "http://localhost:8080"
is not allowed by Access-Control-Allow-Origin.Object
<!DOCTYPE html>
<html>
<head>
<!--
A simple example of PIN-based oauth flow with Twitter and jsOAuth.
This is mostly based on/copied from <http://log.coffeesounds.com/oauth-and-pin-based-authorization-in-javascri>.
Get jsOAuth at <https://github.com/bytespider/jsOAuth/downloads>
-->
<meta charset="utf-8">
<title>jsOauth test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jsOAuth-1.3.4.js"></script>
<style type="text/css" media="screen">
</style>
<script>
$(document).ready(function() {
var options = {
consumerKey: 'YOUR_CONSUMER_KEY',
consumerSecret: 'YOUR_CONSUMER_SECRET'
};
var requestParams;
var accessParams;
var oauth = OAuth(options);
oauth.get('https://twitter.com/oauth/request_token',
function(data) {
console.dir(data);
window.open('https://twitter.com/oauth/authorize?'+data.text);
requestParams = data.text
},
function(data) { alert('darn'); console.dir(data) }
);
$('#pinbutton').click(function() {
if ($('#pin').val()) {
oauth.get('https://twitter.com/oauth/access_token?oauth_verifier='+$('#pin').val()+'&'+requestParams,
function(data) {
console.dir(data);
// split the query string as needed
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {;
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
};
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
getHomeTimeline();
},
function(data) { alert('poop'); console.dir(data); }
);
}
});
function getHomeTimeline() {
oauth.get('https://api.twitter.com/1/statuses/home_timeline.json',
function(data) {
entries = JSON.parse(data.text);
var html = [];
for (var i = 0; i < entries.length; i++) {
html.push(JSON.stringify(entries[i]));
};
$('#timeline').html(html.join('<hr>'));
},
function(data) { alert('lame'); console.dir(data); }
);
}
});
</script>
</head>
<body>
<h1>jsOauth test</h1>
When you get a PIN, enter it here.
<input id="pin" type="text" value=""><button id='pinbutton'>Save</button>
<div id="timeline">
</div>
</body>
</html>
I could give you the answer, but what you're doing is against the Twitter API Terms of Service. OAuthing in JavaScript exposes the secret credentials to anyone who visits the site and that is A Bad Thing. Please do this on your back-end.