I’m detecting if a value has been stored in localStorage (if localStorage exists), and if it’s not in the database (or the user does not have a browser with localStorage) then I run an AJAX GET request.
if (Modernizr.localstorage) {
// there is storage
artist = localStorage.getItem('artist');
if (!artist) {
// but no cache
artist = fetchArtist();
localStorage.setItem('artist', artist)
}
} else {
// there's no storage
artist = fetchArtist();
}
function fetchArtist() {
var fetchedArtist;
var recentTracks;
$.get('script.php', [], function(data) {
recentTracks = data.recenttracks;
fetchedArtist = ((recentTracks !== undefined) ? recentTracks.track.artist['#text'] : 'Last.fm connection failed.');
}, 'json');
return fetchedArtist;
}
script.php just gets a JSON string, which jQuery converts in to the data object. I can see the problem: because $.get is async, the fetchedArtist variable is returned before the function can assign the value I’m after, but I can’t think of a tidy way of doing this (global vars maybe, but I’d really rather not). I can console.log the fetchedArtist var inside $.get and the value I’m after, but the fetchArtist functions always returns undefined.
You have to asyncronize your workflow by removing the return statements from the
fetchArtist()function because it cannot do what you need because of the async behaviour of the$.getrequest.Try something like this:
Hope this helps! Ciao.