0

can you please tell me what i am doing wrong here. i know its simple problem but took whole day for this. all i was trying to do was adding a value to array called messages from json file.

    function get_message(params) {

    var messages = ["hello", "bb"]; // i have manually assigned the value here for   testing purpose
    $.getJSON("messages.json", function( json ) {
        var test="JSON Data: " + json.login.loginsuccess.excited.en[0] ; // this is working fine. just retrieving 1 value for testing 
        console.log(test); // it shows the output get from json file. this line is also fine
        messages.push(test);// here is the problem. why i am not being able to add value to this array messages?

    });
    alert(messages[2]);// it gives me out put undefined
    var index = Math.floor(Math.random() * messages.length);
    return messages[index];
}

thanks

  • Ajax is async. The alert happens before the ajax call finishes and before the new item is pushed into the array. – Jason P Nov 13 '13 at 22:27
  • This issue has already been answered in http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call. – Eric Nov 13 '13 at 22:28

2 Answers2

0

It's because the AJAX call is asynchronous, so the alert() line is firing before the data is pushed to the messages array. Try moving your code to show the alert inside the callback function.

magritte
  • 7,396
  • 10
  • 59
  • 79
0

getJson is asynchronous, so you need to ensure that you're not checking the messages array too soon. You should probably use a callback to get the information you need.

function get_message(params, callback) {
  var messages = ["hello", "bb"];
  $.getJSON("messages.json", function( json ) {
    var test="JSON Data: " + json.login.loginsuccess.excited.en[0];
    console.log(test);
    messages.push(test);
    alert(messages[2]);
    var index = Math.floor(Math.random() * messages.length);
    callback(messages[index]);
  });
}

And use like:

get_message(params, function (data) {
  console.log(data);
});
Andy
  • 61,948
  • 13
  • 68
  • 95