Artur Grigio Artur Grigio - 3 months ago 12
Ajax Question

AJAX not saving variables to javascript (asynchronous issues)

Why is alert saying that the

text[0]
is
undefined
?

This is my code:

var text = new Array;
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
success: function(rows){
text = rows;
}
});
alert(text[0]);

Answer
var text = new Array;
$.ajax({
   url: 'engine1/api.php', 
   data: "", 
   dataType: 'json', 
   success: function(rows){
      text = rows;
      alert(text[0]); // will work, this gets executed after you set text
   } 
});
//alert(text[0]); << don't put this here, it will get executed right after you send the request