5

I am calling a web services from client side on .aspx page, and I want to call a function on the success of this service.

The name of function will be passed as a parameter to this function, which will dynamically change.

I am passing it like this:

function funName parm1, parm2, onSucceedCallFuntion

function onSucceedCallFuntion(result)
//doing something here.    

Perhaps because it's a string is why the "succeed" function could not be called

function funName(parm1, par2, onSucceedFunName) {
    $.ajax({
        url: "../WebServices/ServiceName.asmx/ServiceFunName",
        data: JSON.stringify({
            parm1: parm1,
            par2: par2
        }), // parameter map  type: "POST", // data has to be POSTED                
        contentType: "application/json",
        dataType: "json",
        success: onSucceedFunName,
    });

function onSucceedFunName() {}
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Anu
  • 753
  • 2
  • 13
  • 22

1 Answers1

16

If you're passing the name of the function as a string, you could try this:

window[functionName]();

But that assumes the function is in the global scope. Another, much better way to do it would be to just pass the function itself:

function onSuccess() {
    alert('Whoopee!');
}

function doStuff(callback) {
    /* do stuff here */
    callback();
}

doStuff(onSuccess); /* note there are no quotes; should alert "Whoopee!" */

Edit

If you need to pass variables to the function, you can just pass them in along with the function. Here's what I mean:

// example function
function greet(name) {
    alert('Hello, ' + name + '!');
}

// pass in the function first,
// followed by all of the variables to be passed to it
// (0, 1, 2, etc; doesn't matter how many)
function doStuff2() {
    var fn = arguments[0],
        vars = Array.prototype.slice.call(arguments, 1);
    return fn.apply(this, vars);
}

// alerts "Hello, Chris!"
doStuff2(greet, 'Chris');
sdleihssirhc
  • 42,000
  • 6
  • 53
  • 67
  • What if the callback has arguments? So we'd need to be able to do doStuff(onSuccess(arg1, arg2)); Doesn't work when I try to do that. – jmease Oct 10 '12 at 19:35