0

I need to change the var state on success, but debugging the js code, it doesn't call the success function at all, even though there is success. The state variable remains undefined. I'm not sure why it doesn't change. Looking at the network using firebug, the response is {"d": 1}, which is the value the state should have. Any help is appreciated

var state;

$.ajax({
        url: "isoServe.asmx/GetStatus",
        type: "GET",        
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            state = msg.d;
        }, 
        error: function() {
            alert("Error" );
        }
    }); 

return state;
user1960836
  • 1,732
  • 7
  • 27
  • 47

1 Answers1

0

You should return the state inside the AJAX Call:

var state;

$.ajax({
    url: "isoServe.asmx/GetStatus",
    type: "GET",        
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        state = msg.d;
        return state;
    }, 
    error: function() {
        alert("Error" );
    }
});

In your case, the return statement fires before the AJAX Response could come! As it says, asynchronous, you need to wait till it gets the response.


Update:

You cannot have a response for the AJAX call directly, as it is an asynchronous request. Instead, it can invoke another function in the success callback, such that the function is triggered and states are set.

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252