Search code examples
javascriptjqueryjquery-callback

Callback with Javascript


I have a function x1 that has a ajax call to the server something like below

var result;

function x1()
{
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service        
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server        
        success: function (msg) {//On Successfull service call
            result = msg.GetUrlContentResult; 
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

I have another function x11 that calls x1 that depends on this value of variable result which is global var.

function x11()
{
    x1();
    if (result==something)
    {do something}
}

problem is since x1() is async function the result is not set when the if result get's executed. i think i have to do some type of callback, looking at some examples for callback i am little new to this any help how to correctly setup a callback so value of result is set when it returns from x1? i have more than one function that calls x1()


Solution

  • What you're trying to do is actually something as simple as this: (edited for dynamic callback)

    function x1(callback)
    {
        $.ajax({
            type: Type, //GET or POST or PUT or DELETE verb
            url: Url, // Location of the service        
            contentType: ContentType, // content type sent to server
            dataType: DataType, //Expected data format from server        
            success: callback,
            error: function (xhr, ajaxOptions, thrownError) {
    
            }
        });
    }
    
    x1(x11);
    

    You'll have to modify the x11 function to accept the msg argument and update the result variable:

    function x11(msg) {
        result = msg.GetUrlContentResult;
        //...
    }