FabianCook
FabianCook

Reputation: 20557

Passing a function in javascript

I am trying to pass a function to another function to use in its call back, I call the function using...

call("login", {email:user,password:pw}, alert(getResponse()));

call is defined as:

function call(url, p, f){
    $.getJSON(baseUrl + url, p, f(data));
};

and getResponse is defined as:

function getResponse(d){
    return d.result.success;
};

data is returned by getJSON (see here: http://api.jquery.com/jQuery.getJSON/)

How am I meant to pass data to that function?

The function is called, because it hits a break point I set.

When getResponse is called though I get Uncaught ReferenceError: data is not defined

Upvotes: 2

Views: 79

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382092

Use

call("login", {email:user,password:pw}, function(data){alert(getResponse(data)}));

The expression alert(getResponse()) is the call of the alert function (with getResponse called without any parameter, and thus this would throw an error as d.result would mean taking result from undefined), but function(data){alert(getResponse(data)}) is the definition of a new function taking data as parameter.

Also on a note to that you do not need to have f(data) in $.getJSON(baseUrl + url, p, f(data)); you only require f, so you would call $.getJSON(baseUrl + url, p, f);

Upvotes: 3

Samuel Rossille
Samuel Rossille

Reputation: 19828

The expression alert(getResponse()) pops an alert and doesn't evaluate to a function but to undefined.

You have to pass a function which implementation is alert(getResponse(d)) where d is it's parameter.

Such as the expression function(d){alert(getResponse(d);} for example

Upvotes: 1

Related Questions