Search code examples
javascriptcallbackscopepagemethods

Accessing javascript variables set in Callback function of a PageMethod call


In a click event, I invoke a PageMethods request, which contains two callback functions: OnServerValidationSuccess and OnServerValidationFailure. I also try and set create an object called clientResult;

    var clientResult = { rc: "", msg: "" };

    $('#btnSave').click( function () {
        PageMethods.ServerValidateCreateCompany(companyName, domainName, country, OnServerValidationSuccess, OnServerValidationFailure);
        alert(clientResult.rc); //this is null!
});

In the OnServerValidationSuccess, the result parameter contains the asynchronous response. And in there I try to assign it to clientResult.

//On Success callback
function OnServerValidationSuccess(result, userContext, methodName) {
    clientResult = result;
    if (clientResult.msg.length != 0) {
        document.getElementById('resMsg').innerHTML = clientResult.msg;
        $('#resMsg').addClass('warning');
    }
}

I assign the result to local clientResult variable in the callback function. It should contain the fully formed server response, which is sent correctly by the server-side WebMethod. However, it remains null or empty after PageMethod is called. What must I do in order to assign the variable set in the callback to a local variable so that I can access it?


Solution

  • You seem to be assigning the value to clientResult correctly, you're just accessing it too early.

    You're making an asynchronous/non-blocking call which means that it returns immediately but continues to work in the background. So your JavaScript immediately returns from the call to PageMethods.ServerValidateCreateCompany and moves on to the alert. But your request hasn't had time to complete and your success callback (OnServerValidationSuccess) hasn't even run yet so you get undefined or null.

    You should invoke whatever function is going to process the response in the OnServerValidationSuccess function which is where the response will be received. Perhaps something like this (you already seem to doing something with msg, just move your work with rc here as well)

    //On Success callback
    function OnServerValidationSuccess(result, userContext, methodName) {
        clientResult = result;
        alert(clientResult.rc); //this will work
        process(clientResult); //process the response here
        if (clientResult.msg.length != 0) {
            document.getElementById('resMsg').innerHTML = clientResult.msg;
            $('#resMsg').addClass('warning');
        }
    }