Global variable not set value in $.getJSON properly - javascript

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);
});
});
}

Related

How to set interval for get data from API (jQuery)

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);

Run JS Function on Ajax Success & on Page Load

I have a function newCount that I run on Ajax success and it is working OK, however, I want to also run the same function every time the window is reloaded but for some reason I'm unable to call the function with newCount();
my code:
.ajax
$( document ).ajaxComplete(function() {
newCount();
});
.js
function newCount() {
var sum = 0;
$('.myclass').each(function() {
sum += parseFloat($(this).text());
});
// update count in html
$('#myid').html(sum);
}; // end count function
newCount(); // ajax not working when this in place
when I add newCount(); after the function, it will run correctly on page load, but the ajax will no longer work and vice versa.
What am I missing? How can I call the same function from the ajax success and every time the page is loaded?
Hey I've created this Plunker to show you how you should call the functions.
Here is the Javascript code.
<script>
(function(){
function newCount(msg) {
alert("message from: " + msg);
}; // end count function
debugger;
newCount("Page load");
$.get( "data.json", function( data ) {
alert( "Load was performed." );
});
$(document).ajaxComplete(function() {
newCount("ajax complete");
});
})();
EDIT 1
I've changed the Plunker so you can see that also works inside the $.ajax success property.
$.ajax({
url: "data.json",
data: "",
success: function() {
newCount("ajax complete");
}
});

jQuery each function is not being executed at dynamically loaded content by $.post request

I am trying to loop through elements which are returned as dynamically loaded content via the ajax $.post method. Here is the code:
$.post(ajax_url, {action: 'filter-search-results', term_id: term_id}, function (res) {
$('.job_listings').empty();
$('.job_listings').html(res);
$('.hotel-rate').each(function (i, obj) {
//...
But the each function is not being executed.
When I trigger a click event of body it works:
$.post(ajax_url, {action: 'filter-search-results', term_id: term_id}, function (res) {
$('.job_listings').empty();
$('.job_listings').html(res);
$(document).on('click', 'body', function() {
$('.hotel-rate').each(function (i, obj) {
//...
It works fine. But I don't want to the each to be binded in any event. How can I execute the each function without triggering any event?
Why don't you try this:
var items = $('.hotel-rate');
$.each(items, function (index, value) {........
just like it is explained in the jQuery API documentation
Have you tried looping through the job listings object after it's populated?
$.post(ajax_url, {action: 'filter-search-results', term_id: term_id}, function (res) {
var $jobs = $('.job_listings').html(res);
$jobs.find('.hotel-rate').each(function (i, obj) {
//...

Fire javascript function after get request

I have 2 separate javascript functions, the first builds a dropdown list from a JSON feed and then the second fires the Selectric plugin to style the dropdown.
I added a delay to the plugin function but it's a hack so id like to add this function after the get request finishes.
$(document).ready(function() {
$.get('scanlistjson',{id:''},function(responseJson) {
var $select = $('#scanlist');
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
});
});
setTimeout(function() {
$('#scanlist').selectric();
}, 300);
You have to call it in the $.get call back function after appending the all option of select:
$(document).ready(function() {
$.get('scanlistjson',{id:''},function(responseJson) {
var $select = $('#scanlist');
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
$('#scanlist').selectric(); // call it here
});
});
Put the function call inside callback.
$(document).ready(function() {
$.get('scanlistjson',{id:''},function(responseJson) {
var $select = $('#scanlist');
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
$('#scanlist').selectric();
});
});

Why does my array appear empty when calling a function after the array is built in JS

// variables to be used throughout
var videos = new Array();
// similar artist/bands
function similarTo(who) {
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist='+who+'&limit=20&api_key=b25b959554ed76058ac220b7b2e0a026&format=json&callback=?', function(data) {
$.each(data , function(i,similars) {
$.each(similars.artist, function(c, artist) {
$.getJSON('http://gdata.youtube.com/feeds/api/videos?q='+artist.name+'&orderby=relevance&start-index=1&max-results=1&v=2&alt=json-in-script&callback=?', function(data) {
$.each(data.feed.entry, function(i,video) {
videos.push({
id: video.id.$t.split(":")[3],
title: video.title.$t
});
});
});
});
initPlaylist();
});
});
}
// start the playlist
function initPlaylist() {
$('#ytplayerid').load('includes/ytplayer.php?track=' + videos[currenttrack].id);
$('#player span').html(videos[currenttrack].title);
}
When my code reaches the initPlaylist() function the videos array appears to be empty, I have a feeling its actually being fired before the $.getJSON() call... is this possible? If I add a console.log(videos) after each push() the array is actually being built.
$.each(similars.artist, function(c, artist) {
// doing ajax stuff here
$.getJSON('url', function(data) {
// this will get called later
$.each(data.feed.entry, function(i,video) {
videos.push({
id: video.id.$t.split(":")[3],
title: video.title.$t
});
});
});
});
// trying to manipulate ajax data now :(
initPlaylist();
Your videos is empty because your trying to manipulate it before it's ready.
What you want to do is use jQuery 1.5+ deferred objects
var ajaxs = $.map(similars.artist, function(artist, c) {
return $.getJSON('url', function(data) {
$.each(data.feed.entry, function(i,video) {
videos.push({
id: video.id.$t.split(":")[3],
title: video.title.$t
});
});
});
});
// when all the ajaxs finish then call init play list
$.when.apply($, ajaxs).then(initPlaylist);
Move initPlaylist to a point where videos exists:
function similarTo(who) {
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist='+who+'&limit=20&api_key=b25b959554ed76058ac220b7b2e0a026&format=json&callback=?', function(data) {
$.each(data , function(i,similars) {
$.each(similars.artist, function(c, artist) {
$.getJSON('http://gdata.youtube.com/feeds/api/videos?q='+artist.name+'&orderby=relevance&start-index=1&max-results=1&v=2&alt=json-in-script&callback=?', function(data) {
var videoes = []; //create array
$.each(data.feed.entry, function(i,video) {
videos.push({
id: video.id.$t.split(":")[3],
title: video.title.$t
});
});
initPlaylist();
//videos exists, but i think you might need to pass it as a parameter
});
});
});
});
}
Although, knowing what is in initPlaylist(); might help. And it might solve what appears to be a scope problem in your code.
ALSO: Ajax is asynchronous, there forit might not finish by the time the code gets to initPlaylist();, so you need some type of callback to call initPlaylist(); when all the ajax calls are done.

Categories

Resources