-1

EDIT: Please feel free to delete, I have found an appropriate answer in the duplicates mentioned above. Apologies.

I have the following code, and can't seem to dig the variables out correcly:

$('#button').click(function() {
     alert(getRemaining(0));
}

function getRemaining(i){   
    var x;          
    $.get('files/remaining.txt', function(file){
        x = file.split(",");            
    });
    return x[i]
}

My alert just keeps coming out as undefined. What am I doing wrong?

ms813
  • 241
  • 3
  • 17

1 Answers1

1

the .get that you run is an asynchronous function. This means that execution of your code will continue on past it BEFORE it completes. The callback function that you pass into .get will be called once it is finished (this is the main reason for providing a callback).

This code will alert once the .get has returned.

$.get('files/remaining.txt', function(file){
    x = file.split(",");   
    alert(x[0]);         
});
  • thanks for the explanation, but how do I get `x` out of the `.get` function and useable in a different part of the code after `.get` has finished? – ms813 Aug 15 '13 at 18:19
  • 1
    You won't be able to access x until your callback is called. I'd recommend any code that relies on x be placed into the callback function (if there's a lot of code, you might want to put it into a separate function, then call THAT function inside the callback). If you really need x outside the code somewhere, define a global variable `var global_x = undefined;`, then set it inside your callback. Then anywhere else you need x, be sure to check to make sure it's not undefined before using it. –  Aug 15 '13 at 18:20
  • Great I think that's done the trick :) – ms813 Aug 15 '13 at 18:26