0

i have below code, here i need to get time variable from getTime?

    function getTime(handleData) {
            return $.ajax({
          url: 'data',
        success:function(data) {
           handleData(data); 
              }
            });
           }


   getTime(function(output){

     if(output == null || output == undefined)
     console.log("data is null");
     arr1 = output.split('\n');

       var time= arr1[0];
      return time
      });

If i try to get time value as below its giving undefined

 var time =getTime(function(output){

 if(output == null || output == undefined)
 console.log("data is null");
 arr1 = output.split('\n');

   var time= arr1[0];
  return time
  });
sree
  • 121
  • 1
  • 18
  • You can not return from an asynchronous call. – epascarello Mar 12 '14 at 13:11
  • but if i do alert(time) , its displaying, is there any way to return the value?? – sree Mar 12 '14 at 13:12
  • If you put a debugging breakpoint in the `success` callback on `$.ajax()` what is the value of `data`? What is the response that comes back from the server? Also, as @epascarello indicates, that `return` statement isn't going to do what you think it does. `getTime` has no return value, and the callback function therein has no place to return the value. You need to actively respond to the value in the callback, not return it. – David Mar 12 '14 at 13:13
  • here data contains the strings which are separated by a new line – sree Mar 12 '14 at 13:15
  • The random indentation makes this difficult to read. In any case, when you're dealing with asynch calls you want to do the work in your success handler. – Dave Newton Mar 12 '14 at 13:15

1 Answers1

1

You are returning the callback function of $.ajax call, not the main getTime function, therefore you'll always get undefined. to properly return from the function and use the value afterwards you should either use the callback function to do your job, or use async:false to make a synchron call.

var timeVal;
function getTime() {
    $.ajax({
       url: 'data',
       async: false,
       success:function(data) {
           timeVal = data; 
       }
    });
}


getTime();
output = timeVal;
if(output == null || output == undefined)
     console.log("data is null");
arr1 = output.split('\n');
var time= arr1[0];
Volkan Ulukut
  • 4,230
  • 1
  • 20
  • 38