Odometer.js Keeps Updating From 0 - javascript

I'm working on a counter that shows the total amount of trees from TeamTrees.org (I'm new to JavaScript) Which I wanted to make it real-time. So, I use Odometer.js and it keeps updating from 0.
Here's the video to describe my problem.
removed
I've tried searching on this site, and other Sites. But, it still didn't work.
Here's the code:
index.html
</div>
<script src="trees.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/odometer.js/0.4.8/odometer.min.js"></script>
<script>
init();
var TreeCount = new Odometer({
el: document.querySelector('#cash'),
auto: 'true',
format: ',ddd',
theme: 'default'
})
</script>
</center>
</body>
Trees.js
function init() {
fetchTrees()
setInterval(fetchTrees, 3000);
}
function formatNumber(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function fetchTrees() {
$.ajax({
url: "-",
method: "POST",
data: {
"wrapAPIKey": "-"
}
}).done(function(data) {
numTrees = data["data"]["#totalTrees"];
$("#cash").text("$"+formatNumber(numTrees))
TreeCount.update(numTrees);
});
}

I think that you need to add the last retrieved value to the new value like so :
function init() {
fetchTrees()
setInterval(fetchTrees, 3000);
}
function formatNumber(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function fetchTrees() {
$.ajax({
url: "-",
method: "POST",
data: {
"wrapAPIKey": "-"
}
}).done(function(data) {
numTrees += parseInt(data["data"]["#totalTrees"]);
$("#cash").text("$"+formatNumber(numTrees))
TreeCount.update(numTrees);
});
}

Related

Chosen plug-in is not working when i create the element dynamically

Chosen plug-in is not working when i create the element dynamically
i created Select list dynamically from ajax response and the problem is Chosen plug-in not working with it , Please help me to solve it
here is my code:
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: '/Home/GetSubCategoriesByAjax',
type: 'GET',
datatype: 'Json',
data: { id: ID },
success: function (data) {
if (data.length > 0) {
console.log(data)
$("#SubListSelect").empty();
var $SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>');
$SubListSelect.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
$SubListSelect.append('<option value=' + value.SubCategoryId + '>' + value.SubCategoryName + '</option>');
});
$("#Div1").empty();
$("#Div1").append($SubListSelect);
}
else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
and and plugin code:
$(document).ready(function ($) {
$(function () {
$("#SubListSelect").chosen();
});
Thank you
My proposal:
in my demo I used a different url for the ajax and I figured out a possible HTML.
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: "https://api.github.com/users",
type: 'GET',
dataType: "json",
data: { id: ID },
success: function (data) {
if (data.length > 0) {
var SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>')
.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
SubListSelect.append('<option value=' + value.id + '>' + value.login + '</option>');
});
$("#Div1").empty().append(SubListSelect);
$("#Div1").find(SubListSelect).chosen()
} else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
$(document).ready(function ($) {
$("#SubListSelect").chosen();
$('#btn').on('click', function(e) {
GetSubCategories('1');
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<!--
The next two lines are the include files for chosen plugin
-->
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<div id="Div1">
This is the starting div:
</div>
<button id="btn">Click Me To Create New chosen object into DIV</button>
I assume the select is in #Div1 which you are emptying, then re-appending.
in that case you need to re-initialize it:-
$("#Div1").empty();
$("#Div1").append($SubListSelect);
$("#SubListSelect").chosen();
A better option though would be to only empty the select and re-append the options to the select without emptying the #Div1. then call:-
$("#SubListSelect").trigger("chosen:updated");
also, this
$(document).ready(function ($) {
and this
$(function () {
mean the same thing, with the latter being short hand. Therefore you only need one.

Alerting string using document.getElementById().innerHTML

I'm trying to alert a string, using document.getElementById().innerHTML, but it's alerting the code of the whole page, instead of the string inside the div. I need it to alert '121'. What am I doing wrong?
<script type = "text/javascript">
function getUrban(pageNum, stopAt, gotoUrl) {
var currentPage = "currentPage";
$.ajax({
type: "POST",
url: gotoUrl,
data: { pageNum : pageNum },
error: function(xhr,status,error){alert("error");},
success:function(data) {
document.getElementById("output").innerHTML = data;
currentPage = document.getElementById("output").innerHTML;
},
complete:function(data) {
alert(currentPage);
} //end of complete:function(data)
});
} //end of function getUrban(pageNum)
getUrban(121,422,"test.php");
</script>
<div id = "output"></div>
Output in Alert:
The full code of the whole page, plus some more code about setting the width.
Output in div with id 'output':
121
Need Alert:
121
test.php
$pageNum = $_POST['pageNum'];
echo $pageNum;
Since you're using jQuery to do the ajax why don't you use jquery for everything else also.
$('#output').text();
Will get only the text inside the div. Not the html elements as well.
It drives me crazy to see people using jQuery and have document.getElementById('id') in their code. You do realize that $('id') will get the same element but with jQuery wrapper so you can use jQuery functions on it. And it's so much shorter to type.
<script type = "text/javascript">
function getUrban(pageNum, stopAt, gotoUrl) {
$.ajax({
type: "POST",
url: gotoUrl,
data: { pageNum : pageNum },
error: function(xhr,status,error){alert("error");},
success:function(data) {
$("#output").html(data);
},
complete:function(data) {
alert($('#output').text());
} //end of complete:function(data)
});
} //end of function getUrban(pageNum)
getUrban(121,422,"test.php");
</script>
<div id = "output"></div>

Repeat the function for every 1 min?

i am calling a function with parameters from onclick method what i want to do is i want this function to repeat every 1 min here is html code:
I am calling a function on everyclick with some parameter as id
The id fetches the the lat longs,and it is plotted in map ,i have done everything working except that i get the data keep recieving from the back end so what i want to do is , as i have clicked the href i want that particular id to be sent and keep recieve the data of that particular id only and when i click the second the first should be stopped and start the another .
<html>
</head>
<body>
</body>
</html>
javascript:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
Try this...
Use setInterval to call function every 1 minute and "trigger" function to click automatically when call function "test"
<html>
</head>
<body>
sdsd
sdsd
</body>
</html>
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
function test() {
$(".todo").trigger("click");
}
var refreshId = setInterval(test, 60000);
You can simply call a setInterval inside your todo function and it will fire with different calls, change your function like this:
function todo(id) {
setInterval(function() {
/*$.ajax({
type: "GET",
url: "example?value=" + id,
dataType: "text",
success: function(data) {
//parsing;
});*/
console.log(id);
}, 1000);
}
link1
link2
I used only 1000 milliseconds for test here, you only have to change it to 60000 to fit your needs, you can see the results in the console..
Note:
Keep in mind that for each click you will fire a new setInterval() so you have to disable click events after the first setInterval() to avoid this problem.
It is not clear as to what constraints you may require from your question and comments, but perhaps something like this?
Repeat will be stopped if there is an ajax error.
Clicking a button will cancel the current repeat and immediately start the new repeat (1-4). Requests in progress are not cancelled and there is no checking included to ignore processing them upon complete.
A stop button is included, this will stop the repeat but not the request in progress.
The requests are async and no effort has been made to make sure that they are processed in order of request.
This is a very basic example that starts you moving in the right direction.
var pre = document.getElementById('out'),
interval = 5,
running = false,
fetching = false,
timerId;
function stop() {
clearInterval(timerId);
running = false;
}
function todo(id) {
fetching = true;
$.ajax({
type: 'GET',
url: 'http://jsonplaceholder.typicode.com/albums?id=' + id,
dataType: 'jsonp',
error: function (qXHR, textStatus, errorThrown) {
pre.textContent += id + ': ' + textStatus + '\n';
stop();
},
success: function (data) {
pre.textContent += id + ': ' + data[0].title + '\n';
},
complete: function () {
fetching = false;
}
});
}
function start(id) {
if (running) {
stop();
}
running = true;
if (!fetching) {
todo(id);
}
timerId = setInterval(function () {
if (!fetching) {
todo(id);
}
}, interval * 1000);
}
document.body.addEventListener('click', function (evt) {
var target = evt.target;
if (target.classList.contains('album')) {
start(target.value);
}
}, false);
document.getElementById('stop').addEventListener('click', function () {
stop();
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="album" value="1">1</button>
<button class="album" value="2">2</button>
<button class="album" value="3">3</button>
<button class="album" value="4">4</button>
<button id="stop">stop</button>
<pre id="out"></pre>
You can use setTimeout of javascript.
It will repeat given function in specified time interval.
Javascript setTimeout function repeat
OR
setInterval( function(){ todo(id);}, 60000);
Make use of setTimeout to call the function again:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
setTimeout(function(){todo(id)}, 60000);
}
And if you also want to clear timeout on some condition:
var timer;
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
timer = setTimeout(function(){todo(id)}, 60000);
if(//Your condition){
window.clearTimeout(timer);
}
}

create twitter like follow button

I have been trying to create a twitter follow button. I followed some recommendations and the end result is not satisfactory. Last time it was working, and now I cannot put it to work besides all my efforts.
I would thought this would be more less simple and it has actually been a challenge!
Check code below (HTML, PHP, JS)
HTML
<button class="btn btn-follow cenasparvas" id="<?php echo $profile_data['user_id']; ?>" type="button" onclick="status();"> Follow
JS (to actually update the database)
<script type="text/javascript">
function status()
{
var this = $('.btn-follow');
var userid = $this.attr("id");
var datastring = 'user_id=' + userid;
if (!this.hasClass('follow')) {
$.ajax({
type: "POST",
url: "follow.php",
data: datastring,
success: function(html)
{
alert('sucess');
}
});
} else if (!this.hasClass('btn-danger')) {
$.ajax({
type: "POST",
url: "unfollow.php",
data: datastring,
success: function(html)
{
alert('sucess aassss');
}
});
}
}
JS (the script that changes the type of button that appears - with support of bootstrap)
<script type="text/javascript">
var btn = $('.btn-follow');
btn.click(h);
btn.hover(hin, hout);
function hin() {
if (btn.hasClass('follow')) {
btn.text('Unfollow');
btn.removeClass('btn-success');
btn.addClass('btn-danger');
} else {
btn.addClass('btn-follow');
}
}
function hout() {
if (btn.hasClass('follow')) {
btn.text('Following');
btn.removeClass('btn-danger');
btn.addClass('btn-success follow');
} else {
btn.removeClass('btn-danger');
}
}
function h() {
if (btn.hasClass('follow')) {
btn.removeClass('btn-success follow');
btn.text('Follow');
btn.removeClass('btn-danger');
} else {
btn.text('Following');
btn.addClass('btn-success follow');
}
}

Javascript status loop

Ok, simple thing in javascript that I could not solve even searching on the web. I guess I even found the right thing but could not put on the right place.
This code tells me if a stream is online or offline. But how do I do to the status and keep updating every 5 seconds?
$(function () {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else {
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
});
Example :
var myAjaxCall = function() {
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
// todo
}
};
var ResInterval = window.setInterval(myAjaxCall, 60000); // 60 seconds
To Stop:
window.clearInterval(ResInterval);
use set time out function
setTimeout(function(){
//your function
foo();
},1000);
Try this out:
function checkStatus() {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else{
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
}
$(function() {
setInterval(checkStatus, 5000);
});
This calls the function checkStatus every 5000 milliseconds (5 seconds).

Categories

Resources