-1

I found this question which is almost exactly the same: Return value from nested function in Javascript

The problem is that the function is passed to jQuery's $.ajax function. Here's what i have:

function doSomething() {
    // Do some stuff here
    console.log(getCartInfo());
}

function getCartInfo() {
    var url = blog_location + '?reqCartData=1';

    $.ajax({
        url: url,
        type: 'get',
        success: function(data) {
            return data;  <------------- This
        }
    });
}

I need to return data to the doSomething function, if that makes sense. I tried to return the entire $.ajax function but that returned the whole object. Any ideas?

Community
  • 1
  • 1
qwerty
  • 5,166
  • 17
  • 56
  • 77
  • 3
    This is asked on a daily basis. See [How to return the response from an AJAX call from a function?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call-from-a-function) – Fabrício Matté Mar 08 '13 at 12:16
  • @FabrícioMatté You're right, sorry. *Edit:* Voted to close! – qwerty Mar 08 '13 at 12:24

2 Answers2

0

Send a callback function:

function getCartInfo(onSuccess) {
    var url = blog_location + '?reqCartData=1';

    $.ajax({
        url: url,
        type: 'get',
        success: function(data) {
            onSuccess(data);
        }
    });
}

getCartInfo(function(data) {
    console.log(data);
});
Catalin
  • 11,503
  • 19
  • 74
  • 147
0

try this

 function doSomething(date) {
    ........your data
}

function getCartInfo() {
    var url = blog_location + '?reqCartData=1';

    $.ajax({
        url: url,
        type: 'get',
        success: function(data) {
           doSomething(data);
        }
    });
}
PSR
  • 39,804
  • 41
  • 111
  • 151