Passing multiple arguments to onSuccess/onFailure function in Prototype

While using Prototype framework for using Ajax operations we use the OnSuccess function quite frequently. Calling an Ajax function in Prototype is quite simple and the basic syntax goes like this.

new Ajax.Request('testurl',{
                method: 'post',
                parameters: {param1:"A", param2:"B", param3:"C"},
                onSuccess: fnSccs,
                onFailure: fnFail
                })

And my onSuccess function :-

function fnSccs(response)
{
        alert(response.responseText);
}

But when i  had to pass multiple arguments to onSuccess/onFailure function i didn’t find any helpful links searching. Finally forums came to the rescue and i had to rewire the code as below:-

new Ajax.Request('testurl',{
                method: 'post',
                parameters: {param1:"A", param2:"B", param3:"C"},
                onSuccess: mySuccess('myValue1', 'myValue2'),
                onFailure: fnFail
                })

function mySuccess(param1, param2){
  return function(response){ // Your old success function
    alert(param1);  // The parameter still accessible here
    alert(param2);
    alert(response);
  }
}

What happens is that when you call mySuccess(…) your old function is returned, but you still have access to the parameters because the variables remain allocated on the outer closure. To know more about javascript closures go here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: