Reputation: 1449
I have declared this function in .js file and calling it in .html file.
function getTotalPages() {
var valuePage;
$.getJSON('Data/product.json').
done(function(data) {
$.each(data, function(key, value) {
valuePage=value;
});
});
//alert('out');
return valuePage;
}
The above function returns the "undefined" without "alert", with alert it is working good. Can any one help me on this.
Thank you In advance.
Upvotes: 0
Views: 297
Reputation: 25682
It's not working because your ajax request is asynchronous.
With alert you have a timeout after which the value is returned. You can make your script work by adding async: false
(note for cross-domain requests using jsonp
you cannot make synchronous request!) but actually I don't recommend you because your JS will block until the request is ready. Better approach is to use a callback:
function getTotalPages(callback) {
var valuePage;
$.getJSON('Data/product.json').
done(function(data) {
$.each(data, function(key, value) {
if (typeof callback === 'function') {
callback(value);
}
});
});
}
Here is an example how you can do this using asynchronous request:
function getResult(callback) {
var url = 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=mgechev&count=3';
$.ajax({
url: url,
success: function (data) {
if (typeof callback === 'function') {
callback(data);
}
},
dataType: 'jsonp'
});
}
getResult(function (data) {
var variable = data;
alert(variable);
});
JSFiddle: http://jsfiddle.net/vWnHJ/
In the example I pass function to the getResult
function and call the given function with the data received from the request.
Upvotes: 2
Reputation: 94121
AJAX is asynchronous, by the time you close the alert message the returned value will be resolved, but without the alert it would be too early. You can either make a synchronous request or use a callback.
Upvotes: 1
Reputation: 16564
This issue has been answered a thousand times. It's about 'there is no way to return any value from an asynchronous request'. Everything you want to do with valuePage
you should do inside the done
callback.
Upvotes: 4