Reputation: 533
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);
}
Upvotes: 0
Views: 1671
Reputation: 8606
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);
});
});
}
Upvotes: 0
Reputation: 457
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); } );
Upvotes: 0
Reputation: 7536
Simply because your alert()
is processed faster than your counter++;
Your .getJSON()
is simply an AJAX-Call which is asynchronous.
Which means the JavaScript code, does not wait until your AJAX Call is finished, it continues without waiting.
Upvotes: 1
Reputation: 337570
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);
}
);
}
Upvotes: 3
Reputation: 33865
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.
Upvotes: 1
Reputation: 1800
function getCounter(param)
{
$.getJSON("somewebserviceURL&format=json&callback=?",
function(data)
{
$.each(data, function(i, item)
{
counter++;
});
// try this
alert(counter);
}
);
}
Upvotes: 0