0
    function getCChatStatus() {
    jQuery.ajax({
        type: "POST",
        url: "index.php?page=CChatAction",
        data: { action: "getStatus" }
    }).done(function(msg) {
        var cChatStatus = jQuery.parseJSON(msg);
        return cChatStatus;
    });
}

function CChatOptions() {
    var test = getCChatStatus();
    alert(test);
}

is returning "test is undefined". How to solve this issue? I already tried async: false.

Thanks

Chris
  • 4,255
  • 7
  • 42
  • 83
  • possible duplicate of [Return Value from inside of $.ajax() function](http://stackoverflow.com/questions/8187201/return-value-from-inside-of-ajax-function) – JJJ May 31 '12 at 10:59

4 Answers4

2

The ajax function is asynchronous and has'nt returned yet when you are calling the alert.

function getCChatStatus(callback) {
    jQuery.ajax({
        type: "POST",
        url: "index.php?page=CChatAction",
        data: { action: "getStatus" }
    }).done(function(msg) {
        var cChatStatus = jQuery.parseJSON(msg);
        callback.call(cChatStatus);
    });
}

function CChatOptions() {
    getCChatStatus(function(test) {
        alert(test);
    });
}

You could also do:

function getCChatStatus() {
    var CChat = jQuery.ajax({
        type: "POST",
        url: "index.php?page=CChatAction",
        data: { action: "getStatus" }
    });
    return CChat;
}

function CChatOptions() {
    var cChatStatus = getCChatStatus();
    cChatStatus.done(function(msg) {
        alert(jQuery.parseJSON(msg));
    });
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

If you use asynchronous functions like jQuery.ajax, you will have to use callback functions to evaluate the results.

Thus, your getter has to be asynchronous:

function getCChatStatus(callback){
  jQuery.ajax({/*...*/})
  .done(function(){
     callback(jQuery.parseJSON(msg))
  })
}

And your test will have to look like:

function CChatOptions() {
  getCChatStatus(function(status){
    alert(status)
  })
}
Leonhardt Wille
  • 557
  • 5
  • 20
0

Your getCChatStatus() function is not returning anything. Even with async: false, your function needs to return the return value of the $.ajax() call. Consider returning the actual observable object that you get from an async $.ajax() call and working with that, instead of running synchronous AJAX requests.

lanzz
  • 42,060
  • 10
  • 89
  • 98
-1

Try this should work !!

 function getCChatStatus() {
        $.ajax({
            type: "POST",
            url: "index.php?page=CChatAction",
           success:function(msg){
            var cChatStatus = jQuery.parseJSON(msg);
            alert(cChatStatus); //if this alert works then that test will work..
            return cChatStatus;
        });
    }

    function CChatOptions() {
        var test = getCChatStatus();
        alert(test);
    }
Kabilan S
  • 1,104
  • 4
  • 15
  • 31