1

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]);

2 Answers 2

1
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
Sign up to request clarification or add additional context in comments.

Comments

0

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).

1 Comment

there's no reason to remove async, the alert should just be in the onsuccess continuation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.