I’ve been working on some simple AJAX functions recently, using MooTools. My problem lies in the code immediately following:
function changePage(id, url) {
var c = false,
r = null;
for (i = 0; i < history.length; i++) {
if(history[i]['id'] === id) {
console.log('cached');
r = history[i].response;
c = true;
}
}
if(!c) {
makeRequest(url, function(response) {
r = response;
history.push({id: id, response: response});
});
}
changeBackground('_background', {color: r.bgColor, image: r.bgImage});
lightboxContents(generateArticle(r.article.id, r.article.title, r.article.body, r.article.timestamp));
return true;
}
Here, whenever the code is executed (it’s routed via a click), I’m sent the error “‘r’ is not defined” – a statement that, in my opinion, is woefully incorrect.
I have, for that matter, also tried replacing ‘r’ with a global variable using the ‘window’ object – same problem.
I’m ever puzzled by this simple problem, and would be worlds grateful if someone with fresh eyes could point out my error.
Thanks for your time!
Timon
ris most likely undefined because it looks likemakeRequestis an asynchronous AJAX call, meaning that its callback function is only invoked once the request completes. Since the call is asynchronous, the JS runtime does not wait there, and continues executing the statements after it, which in your case are the calls tochangeBackground, andgenerateArticle. However, as the AJAX call has not returned by this time and the callback hasn’t been invoked,ris still null. So trying to access any property onrliker.bgColorwill throw aReferenceError.