Valamas
Valamas

Reputation: 24729

Execute dynamic function with param in javascript

If the following possible? I wish to move the alert(result) into a function and to dynamically call it.

Current

$.ajax(this.href, {
    success: function (result)
    {
        alert(result);

        AjaxComplete();
    }
});

My Attempt - not working

$.ajax(this.href, {
    success: function (result)
    {
        window["MyAlert(result)"]();

        AjaxComplete();
    }
});

function MyAlert(result)
{
    alert(result);
}

Is this possible?

Upvotes: 0

Views: 67

Answers (2)

valentinas
valentinas

Reputation: 4337

window["MyAlert(result)");

is invalid syntax (missmatching [ and ), wrong function name, and not calling it at all, just getting it..). Should be

window["MyAlert"](result);

if you want to call it like that, but I see no reason why you couldn't just call it normally, as Blender mentioned.

Upvotes: 1

Blender
Blender

Reputation: 298136

Why can't you just do this?

MyAlert(result);

If MyAlert is a part of the window object, it's already a global.

Unless you want to call an arbitrary function by name (which isn't really good practice, IMO), which you can do like this:

window[function_name_string](argument);

Upvotes: 3

Related Questions