-1

This is probably a crazy stupid question, but I don't get why the things variable is not being reset. Here's what I have:

var things = "";

    jQuery.get("/Users/MyName/Documents/File.txt", function(data) {

        things = data;

      });

    console.log(things)

Whenever I do the console log within the function, it works. When I take it out of the function, it doesn't work. I thought I was setting the things var globally but apparently not?

Jake
  • 733
  • 2
  • 7
  • 18
  • 1
    AJAX is asynchronous (that's what the first A stands for). Your `console.log()` runs before the request returns – blgt Feb 05 '15 at 20:14
  • .get is a call back function. So itis called when the ajax request returns. meanwhile the code continues and the console.log has already been triggered – Simon H Feb 05 '15 at 20:14
  • Gotcha, thanks a lot! How would I accomplish this then, is there a way for me to wait for it to finish? – Jake Feb 05 '15 at 20:15
  • @Jake technically yes, but you don't want to do that. – Kevin B Feb 05 '15 at 20:17

1 Answers1

-3
var things = "";

    jQuery.get("/Users/MyName/Documents/File.txt", function(data) {

        things = data;

      }).done(function() {
       console.log(things);
      });

is same as

var things = "";

    jQuery.get("/Users/MyName/Documents/File.txt", function(data) {

        things = data;
         console.log(things);
      });

Passing a function as second param into $.get, it will be called when AJAX request is succesfull(aka status = 200);

If you want to use it outside, your have to use done() method, and first param(a function) is called if successfull, second on error and third is always.

Starmetal
  • 740
  • 6
  • 14