1

Possible Duplicate:
How to return the response from an AJAX call from a function?

Trying to return data to var pNow that called .get function.

/* set var to server side script */
var pNow = getStime();

function getStime() {
$.get('servertime.asp', function (data) {
  return data;
  //alert(data); 
});
}

alert(data) confirms the data is valid and coming from the server side script but not getting returned to the var that called it.

Community
  • 1
  • 1
hillcreative
  • 123
  • 1
  • 10
  • 1
    your $get is a an async call. You need to use a global variable and then assign to that in your success function. – Ravi Y Jan 18 '13 at 05:37
  • The link Musa gave has lots of very relevant information. You'll find your answer there. – Snixtor Jan 18 '13 at 05:38

2 Answers2

2

The callback function in the second argument of $.get is an asynchrononous call and will fire after the getStime function has already finished its execution. You can use deferred.done to get the value as given below.

var pNow;
getStime().done(function(data) { pNow = data; });
alert("Use pNow here" + pNow);
function getStime() {
   return $.get('servertime.asp');
}
Adil
  • 139,325
  • 23
  • 196
  • 197
0

You can do something like this.

/* set var to server side script */
var pNow = getStime();

function getStime() {
  var newData = null;
  $.get('servertime.asp', function (data) {
     newData = data;
    //alert(data); 
  }).complete(function() {
     return newData;
  });

}
insomiac
  • 5,354
  • 7
  • 42
  • 71
  • 1
    Same problem. That `return` will end the inner call-back function, not the `getStime` function. Remember that you enter a new function scope when you do `function() {...}` – nbrooks Jan 18 '13 at 06:01