0

Hi guys^ have such code:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
</head>

<body>
<script type="text/javascript">
var array = [];
$.get("http://wisepla3nt.com/331.txt", 
       function(data) {
           array = data.split(/\r\n|\r|\n/)
       }
);
</script>
<script>alert(array[Math.floor(Math.random()*array.length)]);</script>
</body>
</html>

On alert have undefined. Why? array is global.

Kenji
  • 73
  • 1
  • 8
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – adeneo Sep 28 '13 at 11:13

4 Answers4

5

The function you pass to get is not executed immediately. It is assigned as an event handler and fires when the browser gets a response to the HTTP request.

The response doesn't arrive until after the alert statement has fired.

Do the work that depends on the response in the callback function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Probably because you're alerting before your $.get function has returned.

The $.get method is an Ajax call which means it's asynchronous. Try moving your alert code into the callback method.

royse41
  • 2,310
  • 4
  • 22
  • 29
0

get is asynchronous and you're calling alert right after it and before the response comes from a server

So the array is empty, array.length is zero and Math.random()*0 will return 0 but there's no array[0] so it returns undefined

Adassko
  • 5,201
  • 20
  • 37
0

Move alert() right after array filling string.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
</head>

<body>
<script type="text/javascript">
var array = [];
$.get("http://wiseplant.com/1.txt",
       function(data) {
           array = data.split(/\r\n|\r|\n/)
           alert(array[Math.floor(Math.random()*array.length)]);
       }
);
</script>
</body>
</html>