0

I am trying to show data using Reddit API. When I display it on alert, it gives undefined as a result.

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js" type="text/javascript"></script>
<script>
    var sample;
    $.ajax({ url: 'http://reddit.com/r/forhire.json', success:
        function(data) {
        sample = data;
    }
    });
    alert(sample);


</script>

</body>
</html>

1 Answers1

1

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:

  1. You declare sample
  2. 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.
  3. Your alert triggers with the current value of sample which undefined
  4. 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
  5. 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.

Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90
  • Can you explain why? I come from a C/C++ background. The variable sample's scope is global. –  Aug 19 '17 at 13:32
  • Certainly, I gave it a shot. There's a lot of information on the subject available so i'd recommend looking through a few resources instead of trusting me. It can take a little while to wrap your head around but it will become second nature very soon. I'm still wrapping my head around pointers and memory management so you are leagues ahead of me ;) – Nick Tomlin Aug 19 '17 at 13:45