holyredbeard
holyredbeard

Reputation: 21248

Data that's returning from function is undefined

I have a problem with returning data from ajax to caller function. When I'm console.logging it out it's undefined.

I believe my problem occurs due the fact that js is asynchronous, and when I'm console.logging the data out it's not ready yet. What can I do to solve it?

FooFunction: function(userInput){

    var fooData = FooFunction2(userInput);
    console.log(fooData);     // <--- undefined
},

FooFunction2: function(userInput) {

    $.ajax({
         url:'./php/test.php',
         type:'post',
         dataType:'json',
         data:{ 
             fooData: userInput
         },
         success:function(data) {
             ...manipulating the data...

             console.log(manipulatedData);    // <--- ['foo', 'foo2'];
             return manipulatedData;
         }
    });
},

Upvotes: 0

Views: 93

Answers (2)

David M&#252;ller
David M&#252;ller

Reputation: 5351

The ajax call is asynchronous, so returning will not work. Change your code to use a callback that is invoked when the ajax call has completed.

I changed your code to do that:

FooFunction: function(userInput){
    var callbackfunc = function(ajaxData)
    {
        console.log(ajaxData); //ajax is complete!
    };

    this.FooFunction2(userInput, callbackfunc);
},

FooFunction2: function(userInput, callbackfunc) {

    $.ajax({
         url:'./php/test.php',
         type:'post',
         dataType:'json',
         data:{ 
             fooData: userInput
         },
         success:function(data) {
             ...manipulating the data...

             console.log(manipulatedData);    // <--- ['foo', 'foo2'];
             callbackfunc(manipulatedData);
         }
    });
},

Upvotes: 2

Anoop
Anoop

Reputation: 23208

FooFunction2 is property of object use this.FooFunction2

and you cant return from asynchronous methods. either make ajax call synch or proivde callback.

FooFunction: function(userInput){

    var fooData = this.FooFunction2(userInput);
    console.log(fooData);     // <--- undefined
},

Modified Code

FooFunction: function(userInput){

     this.FooFunction2(userInput, function(fooData){
          console.log(fooData);     // <--- undefined
    });

},

FooFunction2: function(userInput, cb) {

    $.ajax({
         url:'./php/test.php',
         type:'post',
         dataType:'json',
         data:{ 
             fooData: userInput
         },
         success:function(data) {
             ...manipulating the data...

             console.log(manipulatedData);    // <--- ['foo', 'foo2'];
             cb(manipulatedData);
         }
    });
},

Upvotes: 1

Related Questions