I'm sure this is simple, but I'm tripping up over a scope issue in Javascript. I'm doing the following:
$.get(url, function (data){console.log(data);});
This part works fine - I see the string that I want appear in the console. But what I actually want is to take that data variable and place it in a string. Something like this (doesn't work):
string = $.get(url, function (data){return data;});
This gives string
a value of [object XMLHttpRequest]
.
What am I missing?
Oops
Yes, I'm missing the fact that Ajax is, as the name says, asynchronous. Thanks for giving me the slap on the forehead I needed, everyone.
Afterword
The reason I wasn't simply working with the results inside the callback function itself is that I actually need to do multiple AJAX requests every few seconds, gather up the data, and append them all to the page when they're all done.
I've now got that working with a little closure function - the requests are done in a loop, and the data is passed to the closure. When the timer goes off, I call the closure function with no arguments, which tells it "append your previous batch of data to the page (the requests are surely complete by now), clear your cache, and prepare to start receiving new data from the AJAX callbacks in my loop."
Which (hopefully) shows that I'm not an idiot after all. :)