0

So I have a $.get function, which is successfully passing the data back and I'm able to use the data so long as it is processed directly within the $.get function. Is there any way I can pass this data to a global variable?

TheBritishBloke
  • 169
  • 1
  • 2
  • 8
  • 4
    You can use `window.variable="ajax_data"` to set a global variable in JS – Subin Feb 13 '14 at 16:58
  • keep in mind though that you can't run your `$.get` call and then immediately try to use `window.variable` in code after it, since the var won't be popped until after the `$.get` call successfully receives a resonse – CrayonViolent Feb 13 '14 at 17:00
  • Welcome to the wonderful world of **async**! You can't do that. – SLaks Feb 13 '14 at 17:04
  • @SLaks well, you "can" .. it's just not very useful to do it in practice! – CrayonViolent Feb 13 '14 at 17:05
  • The problem I'm having is that the $.get is getting data to fill the table and is then supposed to add that data to the variable I have which contains all the HTML for the table. This variable is then used as $(table).html(htmlvariable) – TheBritishBloke Feb 13 '14 at 17:22
  • @TheBritishBloke then see the question I've linked, please. – John Dvorak Feb 13 '14 at 17:23
  • @Jan Dvorak I've been going through it, but I just can't figure out the explanation of how to implement it. – TheBritishBloke Feb 13 '14 at 17:49
  • I've managed to implement it as it says, and managed to get it working. However it still doesn't help me because the table gets generated before the ajax call is complete. – TheBritishBloke Feb 13 '14 at 18:04
  • If you want to do something after an AJAX call is complete, put it into the callback that you pass to the AJAX call. – John Dvorak Feb 13 '14 at 18:06
  • It still caused the problem of it ending the javascript, and coming back to it once the call was complete, meaning any variables that existed had now been reset. I ended up having to use async:false. It's not for a very big table, and it seems to work ok. I can PM you a link to the site if you have any advice. – TheBritishBloke Feb 13 '14 at 22:03

3 Answers3

4
var storage;
$.get('/some/url', function(data) {
    storage = data;
});

NOTE:

Because $.get is asynchronous, don't expect storage to have anything in it even after executing the $.get

Populus
  • 7,470
  • 3
  • 38
  • 54
0

Method 1

$.get("http://url.com/page", {}, function(data){
 window.variableName=data;
});

You can access the global variable by :

window.variableName

Or

variableName

Method 2

var variableName;
$.get("http://url.com/page", {}, function(data){
 variableName=data;
});

Since $.get is asynchronous, the variableName will only have value when the response is complete.

Subin
  • 3,445
  • 1
  • 34
  • 63
0

You can also do something like this, and you need to understand Javascript object scope

var returnedData;
$.get("url", function(data){
   returnedData =  data;
});
Community
  • 1
  • 1
user2989408
  • 3,127
  • 1
  • 17
  • 15