0

how to return jquery ajax success result

function name (LevelId) {
    var passobj = null;
    $.ajax({
        url: 'GetValues' + '/?LevelId=' + LevelId,
        type: "POST",
        dataType: "json",
        contentType: 'application/json',
        async: false,
        success: function (result) {
            passobj = result;
        },
        complete: function () { },
        error: ServiceFailed// When Service call fails
    });
    return passobj;
}

  returned =name(id);
user930453
  • 71
  • 1
  • 1
  • 13
  • Contrary to what @Niko and @Jim said, your code should work, considering that you correctly set `async = false`. Can you check that the JSON object returned is correct? – Razor Sep 07 '11 at 12:23
  • What doesn't work about this? – yoozer8 Sep 07 '11 at 12:47
  • actually by using alert(returned) it shows as [object Object]. wen i try to drop down this values, the drop down was empty. So i had a doubt in this whether the function return or not – user930453 Sep 07 '11 at 13:44

2 Answers2

3

This worked for me

ajaxCall(urls, data).success(function(data){
    // get the result
});

function ajaxCall(url, data){   
    var result;

    return $.ajax({
        type: 'POST',
        url: url,
        data: data
    });
}
Max Shmelev
  • 3,774
  • 4
  • 26
  • 26
0

That won't work, because the ajax request is performed asynchronous what means that your function returns null - the success event handler is not called until the response from the server is retrieved (what may take some time). You will need to refactor your code using events.

function name(id, callback) {
    $.ajax({
        ...
        success: callback
    });
}

name(17, function(returned) {
    // work with the response...
});

EDIT: Sorry, didn't notice that you set async: false - in that case your code is actually supposed to be working fine, if I don't miss anything again.

Niko
  • 26,516
  • 9
  • 93
  • 110