I have a function which uses getJSON but its not working like I expected.
function balbla(name, param) {
$.getJSON("/blabla.json?name=" + name + "¶m=" + param, function(data) {
return data.bla;
});
}
When I use alert(data.bla) in the getJSON method it works but when I try return data.bla it doesnt. Also when I create a variable and try to write the value of data.bla to it it simply doesnt work!
// I tried this:
function getRouteData(name, param) {
return $.getJSON('/routes_js.json', {route:name, opt: param});
}
function getRoute(name, param) {
getRouteData(name, param).done(function(data) {
return data.route;
});
}
But when I call getRoute("bla", "blub") it still returns undefined.
AJAX is asynchronous. You cannot easily return a value in such a function that depends on the result of the AJAX call. Change your function to accept a callback:
And use it like this:
An even cleaner way would be returning the jqXHR object:
When calling it, use the deferred/promise interface of the jqXHR object to attach a success callback:
Note that using
$.ajax()in synchronous mode is not an option you should consider at all. It may hang the browser’s UI (or at least the active tab) until the request finished. Besides that, asynchronous callbacks are the way everyone does it.If you do not like using callback functions, you could use a preprocessor such as tamejs to generate the asynchronous functions automatically.