Reputation: 1100
I have a quick question on JavaScript:
I have the following line of code shows an example and it works fine. You can access passeddata there are no issues.
$.getJSON(jsonUrl,function(passeddata){
alert("it worked ");
});
The next code sample does not work and fails with the following error:
Uncaught TypeError: Object ReferenceError: passeddata is not defined has no method 'replace' jq.html:177 (anonymous function)
$.getJSON(jsonUrl, something(passeddata));
function something(passeddata)
{
var jasondata = passeddata;
alert("it worked ");
}
Can someone explain the issue? I know its probably something obvious, but I'm just not able to find an answer.
Upvotes: 4
Views: 1300
Reputation: 191729
You don't want to put something(passeddata)
as that calls the function and uses its return value as the callback. What you want is just this:
$.getJSON(jsonUrl, something);
Note that the parameter name does not matter when being used as an argument, so you can still use passeddata
in the function itself.
Upvotes: 1
Reputation: 14434
you are passing the RESULT of "something(passedata)" as second param into the getJSON function call
Upvotes: 2
Reputation: 12815
$.getJSON(jsonUrl, something);
function something(passeddata)
{
var jasondata = passeddata;
alert("it worked ");
}
This is how it should be. With second param you just tell a pointer to function which should be executed. In your code function is executed immediately
Upvotes: 3
Reputation: 5443
try changing the second instance to just pass the callback to the getJSON method. passeddata doesn't exist yet so you just give the function name:
$.getJSON(jsonUrl, something);
function something(passeddata)
{
var jasondata = passeddata;
alert("it worked ");
}
Upvotes: 4
Reputation: 943240
In the first case, you are passing a function to getJSON
that gets executed when the HTTP request for the JSON comes back.
In the second, you are calling the function immediately and passing its return value to getJSON
.
Don't call it yourself, take the ()
away: $.getJSON(jsonUrl, something);
Upvotes: 6