Reputation: 5553
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]);
Upvotes: 1
Views: 97
Reputation: 3603
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
Upvotes: 1
Reputation: 5553
Finally answered my own question, for anyone that comes across this question, here is what I did:
Because ajax is asynchronous, alert(text[0])
is getting executed before text=rows
.
You can set ajax to run procedurally like this:
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
async: false;
success: function(rows){...
Apperently this is one of the few cases that you can/should set ajax to async:false
(because you're serving javascript/jquery to the client).
Upvotes: 0