1

I'm trying to grab a random word from a dictionary file using JQuery - but I'm not able to 'return' the value. The returned value is always "undefined".

function RandomWord()
{
    $.get('dictionary.txt', function(data) {
        var words = data.split("\n");
        var idx = Math.floor(words.length * Math.random());
        word = words[idx];
        return word;
    });
}

However, when I replace "return word;" with "alert(word);" - it does show me the random word.

Any idea how I can fix this?

Brian Smith
  • 1,443
  • 5
  • 18
  • 24

2 Answers2

2

Since it is an $.get(), it's an AJAX GET request. The function is called when a response is received asynchronously, so you can't return from a callback I guess. You may assign it to some element like this:

$('#sample-elem').html(word);

Else you can declare "word" outside the AJAX Call and assign the result to it and do async:false like this

function RandomWord()
{
    var word;
    $.get(
         url: 'dictionary.txt',
         async: false,
 ``      success: function(data) {
         var words = data.split("\n");
         var idx = Math.floor(words.length * Math.random());
         word = words[idx];
    });
    return word;
}
Charizard_
  • 1,215
  • 1
  • 9
  • 20
1

The problem here is that $.get is returning data asynchronously- meaning it could happen immediately, but might not.

The proper answer lies in JavaScript callbacks. I'll let you Google it, but you could start here for a primer.

That, or you could just do whatever you need to do with your word within the RandomWord() function:

console.log(word);

...or you could call another function:

workWithRandomWord(word);

function workWithRandomWord(word) {
    console.log(word);
}
jterry
  • 6,209
  • 2
  • 30
  • 36