0

I'm trying to use $.get() to retrieve data from a server, and assign it to a variable to work with it. For example:

$.get('htmllink', {}, function(results){

//do stuff here

});

var morestuff = ; //$.get() data goes here

The problem is, I can't get anything to work outside the rounded brackets. Everything is treated as internal variables or something. What am I missing?

Alex
  • 23
  • 3
  • why can't you assign the variable inside the callback and do your thing? what is stopping you.? Can you give more cases ? – mohkhan Jul 07 '13 at 03:22
  • That does look like a similar case, I'll check it out. I'm trying to assign it to something outside because my lack of knowledge is causing some weird issues. I'll look into it a bit and post an update. – Alex Jul 07 '13 at 03:41

2 Answers2

2

You need to do all of your processing inside the callback function. This is because the call to $.get only starts an asynchronous request, and then the next line (var morestuff = ...) is executed after the request starts, but before it has completed.

$.get('htmllink', {}, function(results){

    //do stuff with results in here

});
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
1

The problem here is that the $.get request is asynch (Ajax), so there is a timing issue here. The

var morestuff =

will run before the Ajax call returns, so you won't have the value to assign.

You have to interact with the result of the ajax request in the call back to have access to it

$.get('htmllink', {}, function(results){

//all code that depends on results must run inside here

});

//you can't execute code here that depends on the Ajax call
TGH
  • 38,769
  • 12
  • 102
  • 135