I have a simple question: I am using this function for getting prices from CryptoCompare and now I would like set interval for refreshing data without refreshing page. So I have tried this code:
<script>
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
setInterval(getData, 3000);
$(function() {
getData();
});
</script>
But it is not working for me. Can you help me, please?
Edit:
Used on website https://investplus.cz/
You have some convoluted code. I think what you are intending is for your fetch to be called every 3 seconds.
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
This defines you get function. You have a sample call as
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
You are using setInterval incorrectly though, see https://www.w3schools.com/jsref/met_win_setinterval.asp
You have 2 lines here
setInterval(getData, 3000);
$(function() { getData(); });
This is incorrect, getData is only a name for your function. The setInterval function should take your anonymous function with defined parameters like
setInterval($(function() {
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
}), 3000);
Per your JS fiddle, this works for me (removed jquery function and replaced with regular js lambda)
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
setInterval(function() {
getData('btc', 'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD');
}, 3000);
Related
I am getting an id that is not addressable by jquery ("#"+id).something .
At document start I have a :
var g_justClicked = '';
$.ajaxSetup({
beforeSend:function(event){
if(g_justClicked) {
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).tagName);
};
var wOffset = $('#'+g_justClicked).offset();
$('#loading').show();
},
complete:function(){
$('#loading').hide();
}
});
At document end I have another script (all elements with class spinner should set the global variable 'g_justClicked'):
$(document).ready(function () {
$('.spinner').click(function() {
g_justClicked = $(this).attr('id');
console.log('.spinner.click: g_justClicked='+g_justClicked);
});
This works fine, the variable is set and displayed correctly in ajaxSetup.
BUT: referencing it in tagName= or in wOffset = with
$('#'+g_justClicked).
results in
"TypeError: wOffset/tagName is undefined"
Note: all ids start with several characters, t.e. "boxshow12345" is a typical id.
What am I doing wrong?
I think was able to reproduce your scenario here: https://jsfiddle.net/mrlew/qvvnjjxn/3/
The undefined in your console.log is because you're accessing an inexistent jQuery property: .tagName. This property is only available to native HTML Element.
To retrieve the tag name from a jQuery Object, you should use: .prop("tagName"), or access the property accessing the native element with $('#'+g_justClicked)[0].tagName
So, if you change
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).tagName);
to:
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).prop("tagName"));
Will successfully log: g_justClicked=boxshow12345 tagName=BUTTON, as expected.
Note: In order to your logic work, you have to click .spinner first.
Your problem is that your ajax setup runs regardless of whatever you do in the click handler, and it runs before you even setup that handler. The initial value for g_justClicked is empty string, and this is what it tries to access in $('#'+g_justClicked), hence the error.
If you want to click the spinner and then pass the id to the beforeSend, do it like this:
$(document).ready(function() {
$('.spinner').click(function() {
var g_justClicked = this.id; //simplify this a bit
console.log('.spinner.click: g_justClicked=' + g_justClicked);
// call ajax
_setupAjax( g_justClicked );
});
});
function _setupAjax(g_justClicked) {
$.ajaxSetup({
beforeSend: function(event) {
if (g_justClicked) {
console.log('g_justClicked=' + g_justClicked + ' tagName=' + $('#' + g_justClicked).tagName);
};
var wOffset = $('#' + g_justClicked).offset();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
}
UPDATE
If you don't want a separate function, just move your ajax setup into the click handler:
$(document).ready(function() {
$('.spinner').click(function() {
var g_justClicked = this.id; //simplify this a bit
console.log('.spinner.click: g_justClicked=' + g_justClicked);
// call ajax setup
$.ajaxSetup({
beforeSend: function(event) {
if (g_justClicked) {
console.log('g_justClicked=' + g_justClicked + ' tagName=' + $('#' + g_justClicked).tagName);
};
var wOffset = $('#' + g_justClicked).offset();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
});
});
OK #mrlew.
Answer: I tried your .prop appoach, but still got "undefined". Now back to the roots:
The goal is to get the id of any element that was clicked to modify the busy indicators position, while ajax is running. Newly I am back to my original approach, without global variable and parameter passing:
$(document).ready(function () {
$('.spinner').click(function() {
_setupAjax();
});
});
which works, and:
function _setupAjax() {
$.ajaxSetup({
beforeSend: function() {
$('#loading').show();
wJustClicked = $(this).attr('id'); /// <- that doesnt work!
console.log("_setupAjax wJustClicked="+wJustClicked);
console.log('_setupAjax tagName=' + $('#' + wJustClicked).prop("tagName"));
....defining css based on id (no problem)..
which yields "undefined" twice. I tried so many ways to get that f.... id.
#mrlew
thanks a lot for your help. Meanwhile I found the solution. All trouble came from a timing problem. Here is what works (for all DIV, SPAN and IMG of class=spinner and having an id:
$(document).ready(function () {
_setupAjax();
$('.spinner').click(function() {
wJustClicked = $(this).attr('id');
if(wJustClicked == null) alert('Id missing on item clicked');
console.log('.spinner.click! id='+wJustClicked);
var wOffset = $('#' + wJustClicked).offset();
var xPos = Math.round(wOffset.left) + 8;
var yPos = Math.round(wOffset.top) + 4;
console.log(wJustClicked+' offset left='+wOffset.left+' top='+wOffset.top+' xPos='+xPos+' yPos='+yPos);
wDiv = 'loading';
$('#'+wDiv).css('left',xPos);
$('#'+wDiv).css('top',yPos);
});
and the js function:
function _setupAjax() {
$.ajaxSetup({
beforeSend: function() {
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
}
A strange thing remained (I have firebug installed), which I have solved with Math.round: the x and y position come overdetailed like 170.5134577 and 434.8768664 ?!?
I can live with that. But where does this pseudo precision come from?
Again thanks a lot to keep my hope upright.
I am trying to pass $(this) value to a jQuery function. The function is below but does not work. There are no errors in console.
The function is firing because when I place an alert at the top it works.
(function($){
$.fn.calculateHours = function() {
var tbody = $(this).closest('tbody'); // get closest tbody
var table = $(this).closest('table'); // get closest table
var params = table.find('.disguise').serialize(); // parameters
$.ajax({
type: 'post',
dataType: 'json',
url: '/calculateHours',
data: params,
success: function (response) {
// loop over object
$.each(response.rows, function(index, array) {
$.each(array, function(key, value) {
$('#row_' + index).find('.' + key).html(value);
});
});
if($.isPlainObject(response.columns)) {
$.each(response.columns, function(day, hour) {
$('.totalsRow').find('.total_' + day).html(hour);
});
}
$('.totalsRow').find('.grand_total').html(response.grand_total);
}
});
}
})(jQuery);
$(document).on('change', '.disguise', function(e) {
$.fn.calculateHours();
});
Adding functions to $.fn is meant to extend the jQuery object. In other words, you should be calling .calculateHours on your jQuery object:
$(document).on('change', '.disguise', function(e) {
$(this).calculateHours();
});
You want jquery to set the context automatically. To do that just pass a reference to the function as the handler.
$(document).on('change', '.disguise', $.fn.calculateHours);
I am using getJSON to access Vimeo's Simple API, and any objects created on the page by the call, do not react to the rest of the javascript that is on the page. It is probably something simple that I am missing. Here is my getJSON code:
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').prepend('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
});
});
Here you go: http://jsfiddle.net/8t3Xq/1/
This demonstrates loading your <li> thumbs just as your question does, then I show how to easily change one of them. How to "change" them is endless, this is just a simple example of changing the content and background. So you must not have your selectors right.
This is just a snippet, see fiddle for everything...
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').prepend('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
});
});
window.changeIt=function()
{
$('li').first().html("I'm changed!");
$('li').first().css("background-image","");
}
Just make sure the <li>s are present first before your code that changes them is present. Would need to see more of you code to understand when/how that happens.
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').append('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
$( "#galThms li" ).click(function() {
$(this).hide();
});
});
});
try this
there is no way that my answer is so far removed from the problem statement. my guess is that either I somehow errantly posted this answer or the problem was edited. apologies
you could also use:
$(document).on('click','li .playVideo',function(){
//do something
});
i would probably change your #playVideo to a class, if you will have multiple li's
I have declared global variable named counter=0 on my index.html page inside head section
<script>
var counter=0;
</script>
now in my one of function i am setting its value as
function getCounter(param)
{
$.getJSON("somewebserviceURL&format=json&callback=?",
function(data)
{
$.each(data, function(i, item)
{
counter++;
});
});
//I am not able to get the latest value here & in upcoming functions which use this variable
alert(counter);
}
This is because getJSON is asynchronous. This means the counter variable will not have been incremented before alert(counter) is hit. Instead, move the alert to just after your $.each() loop:
function getCounter(param) {
$.getJSON(
"somewebserviceURL&format=json&callback=?",
function(data) {
$.each(data, function(i, item) {
counter++;
});
alert(counter);
}
);
}
That is because getJSON is sent asynchronously. Your alert is called before the success-callback of getJSON. The success-callback isn't called until you have the response, by then alert() has already fired.
Simply because your alert() is processed faster than your counter++;
Your .getJSON() is simply an AJAX-Call which is asynchronous.
http://www.tizag.com/ajaxTutorial/
Which means the JavaScript code, does not wait until your AJAX Call is finished, it continues without waiting.
function getCounter(param)
{
$.getJSON("somewebserviceURL&format=json&callback=?",
function(data)
{
$.each(data, function(i, item)
{
counter++;
});
// try this
alert(counter);
}
);
}
You could probably use a callback for this :
function getCounter(param, callback) {
$.getJSON("somewebserviceURL&format=json&callback=?",
function(data)
{
$.each(data, function(i, item)
{
counter++;
});
callback.call(this, counter);
}
);
}
getCounter(param, function(counter) { alert(counter); } );
All of are true here that GetJson is asynchronous!
Just shift alert() to inside fore each loop to see affected value as per below
function getCounter(param)
{
$.getJSON("somewebserviceURL&format=json&callback=?",
function(data)
{
$.each(data, function(i, item)
{
counter++;
alert(counter);
});
});
}
i want to block my ui until values in my drop down not loaded
my js file code is as follows
$(document).ready(function() {
// Load All Toll Plazas
FillInCascadeDropdown({ userType: -1 }, "#ddlTollPlazas", "/Home/GetTollPlazas/" + -1);
}
function FillInCascadeDropdown(map, dropdown, action) {
$(dropdown).empty();
$.blockUI({ message: '<img src="/Content/images/ajax-loader.gif"/>' });
$.post(action, map, function(data) {
$.each(data, function() {
$(dropdown).append("<option value=" + this.Value + ">" + this.Text + "</option>");
});
}, "json");
$.unblockUI();
}
above code not working on page load.
I think you're problem is you are unblocking as soon as you call blockUI. You need to move the unblock call to a "Success" callback function. The concept of Callbacks are a little tricky. Basically this is the code that runs once the post is successful. I'm sure you've seen this page but refer to the jQuery post page to see where you need to put your callback and here to learn more about callbacks if you need to. Good luck!
Here is how it should look:
function FillInCascadeDropdown(map, dropdown, action) {
$(dropdown).empty();
$.blockUI({ message: '<img src="/Content/images/ajax-loader.gif"/>' });
$.post(action, map, function(data) {
$.each(data, function() {
$(dropdown).append("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$.unblockUI();
}, "json");