Because your ajax request is asynchronous, sample
is undefined at the moment you are passing it to alert
. The alert
needs to be inside of your success callback.
var sample;
$.ajax({ url: 'https://www.reddit.com/r/forhire.json', success:
function(data) {
sample = data;
console.log(sample)
}
});
The asynchronous nature of JavaScript is difficult to understand if you come from a synchronous background. I'd suggest reading an introduction to asynchronous JavaScript or another guide to understand this better. But, I'll do my best to explain the "flow" here. essentially:
- You declare
sample
- You initiate an Ajax request (which uses an XMLHTttpRequest) which is asynchronous by default. The browser begins this request in the background, noting the
success
callback provided to it, and continues on its merry way to the next statement. While this seems terrible, it's actually wonderful! because a single threaded JavaScript environment can dispatch multiple actions without having to worry about blocking execution.
- Your
alert
triggers with the current value of sample
which undefined
- The ajax request (which has been going on in "the background") finishes, since you provided a
success
callback, it invokes it with the returned data
sample
(which is available in the scope of your callback because you defined it in a parent scope) is now assigned to the value of data
If you'd like to understand a little bit more about what is going on behind the scenes, i'd recommend this excellent SO answer.