1

I'm still fairly new to Ajax so bear with me here.

I'm using $.get() to retrieve and read a text file from the server. I need to store the data in a variable outside of scope so that I could use it later.

function some_func() {
    var ex_var = "A";
    $.get("test.txt", function(data) {
        ex_var = data;
        console.log(ex_var);  // Works
    });
    console.log(ex_var);  // Does not work
}

From reading this, I understand why outside of the scope doesn't work. However, it seems that would mean I would need to do everything inside the callback of the $.get() itself, which doesn't seem appealing to do. Is there any better way of storing the data from $.get() so that it could be used later?

Community
  • 1
  • 1
user3064776
  • 119
  • 7
  • 1
    you can't do that because $.get() is asynchronous – Arun P Johny Mar 13 '14 at 06:23
  • get is async request, means it will not wait for the request to complete. better use promises. or use jquery ajax and async should be false – Paritosh Mar 13 '14 at 06:23
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Arun P Johny Mar 13 '14 at 06:24
  • You can declare a variable in global scope and assign the value of `data` from ajax to that variable then you can use it in other calls after completion of ajax. – Amit Garg Mar 13 '14 at 06:30

2 Answers2

0

The Ajax call $.get() is asynchronous (that's what the "A" stands for in "Ajax"). As such, calling $.get() just starts the process of requesting a remote resource. Then, the rest of your code continues executing, including the code directly after your $.get() call (that's why the console.log() located there doesn't work). Then, sometime later the networking call from the ajax request completes and the remote resource is available. At that point in time, the completion callback function for $.get() is called and your data is available.

All code that uses the results of the ajax call should either be in that completion handler or should be called from the completion handler. You can't write synchronous code when using asynchronous ajax calls. You have to adopt a bit of a new way of thinking when using asynchronous functions.

function some_func() {
    $.get("test.txt", function(data) {
        console.log(data);  // Works
        // call some function and pass it the results of the ajax call
        // this is how you continue your code logic 
        // using the results of the ajax call
        callSomeFunction(data);
    });
}

You do NOT want to try putting data into global variables because you will never get the timing right. The data from the ajax call comes back at an indeterminate time in the future. You should use that data from the completion handler WHEN the data is actually returned and then you won't have to worry about the timing.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • But then like I said, that would mean it seems to be more appropriate to just make the $.get() to be the "main()", so to speak, instead of being used in some other function. I was just wondering to see if there was more of a "better" way of doing that since tossing all the subroutines of the program within a callback seems strange. – user3064776 Mar 13 '14 at 06:37
  • @user3064776 - that's how asynchronous programming works. It uses callbacks. If you put `$.get()` inside another function, then you just have to pass into that other function a callback function that will get called when the data is available. Get used to it. That's how async programming works, period. There are different styles of async programming such as promises if you prefer that, but you will still have the same basic issue. Your code will have to continue after the Ajax call in a callback. – jfriend00 Mar 13 '14 at 06:39
-1

Whether or not to use global variable, it's your choice, global variables are bad and if you don't know why, you need to read more. So i offered my help to you on your specific question on how to "use data for later", which is in other words:

How do i assign the result from a XHR outside a function scope?

Simple, just assign it

<script>
    function some_func() {
      var ex_var = "A";
      $.get("test.txt", function(data) {
            ex_var = data;
            console.log(ex_var);  // Works
        }).done(function() {
          console.log(ex_var);  // Does not work <-- will work now
        });
    }        
</script>
Lee Gary
  • 2,357
  • 2
  • 22
  • 38