0

Here is a code snippet

var translatedWord = "";
currentCharacter = "猫";
translateRequestURL = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=zh-CN&tl=en&dt=t&q=' + currentCharacter;
$.ajax(translateRequestURL).done(function (data) {
    translatedWord = data[0][0][0]; //this is what I need
  alert('This works '+translatedWord); //this works
});

alert('this does not '+translatedWord); //this doesn't work

Here is a fiddle if the code above https://jsfiddle.net/ovntx1c1/

I basically need to get the translatedWord (cat, in this case) to be able to use after the function translates it. I am seeing from the fiddle that my alert outside the function kicks off first, I imagine that's because I am not actually calling the function so functions run last, which is probably my issue.

I tried changing "function (data)" to "function someFunction (data)" so its named and then afterwards call testing(), but I didn't exactly know what to put in the parenthesis. I also tried to "return translatedWord" at the end of the function.

I made a fiddle for that attempt: https://jsfiddle.net/ovntx1c1/2/

I know this has been posted more than a few times and I run the risk of being downvoted but I just can't figure out what I am doing wrong.

  • It's not scope, it's timing. See the linked question's answers for details. In your code above, you're trying to use `translatedWord` before the ajax callback runs. – T.J. Crowder Jun 11 '17 at 13:54
  • Oh! So it has to do with the fact I am pulling in from AJAX, I didn't think to factor that in or even the words to search for. I'll take a look at that, thank you for finding that for me! My guess is it takes a few milliseconds to run but the item after it runs instantaneously? – Shawn Hellwege Jun 11 '17 at 15:16
  • Yup! I set a 1 second delay in there and it worked wonderfully, what I need to run with it doesn't kick off for several seconds so that works perfectly, thank you! – Shawn Hellwege Jun 11 '17 at 15:21
  • Don't use a delay, it's fragile; what if the ajax call hasn't completed by the time the delay finishes? Instead, use the techniques described in the answers to the linked question. – T.J. Crowder Jun 11 '17 at 15:26
  • Thanks for the tips, my adviser gave me a difficult (for me) addition to do for my masters project on Friday before I present tomorrow so as much as I truly think promises would be the way to go I don't have time to learn/implement/test that out by then. I will put it as a task to implement in the future. Adding the referred SO to my notes. Thanks! – Shawn Hellwege Jun 11 '17 at 19:48

0 Answers0