Tuesday 21 August 2012

Javascript remote method invoke in VF page

How to invoke an Apex class method in java script code ????

Possible solution for this are:
  1. Remote method call
  2. Webservice call
Among these 2, Remote method call is preferred as it is faster and reliable. If possible, try to avoid Webservice call in java script method, as this counts to salesforce limit (Very important) .






Remote method call

For remote method call, the Apex Class should be declared as global and method to invoke should be declared as remote action method as:

@RemoteAction
global return_type methodName(params) {}

This is how a method is declared as remote method in class.

Method may be invoked by remote action in a javascript code as:

OrgNamespace.ClassName.MethodName( param1, param2,..., function(result, event) {
    if(event.type == 'exception') {
        alert(event.message);
    } else {
        //    Success logic
    }
}, {escape:true});

I think, here all the names are self explanatory.


Webservice method call

For webservice method call, method should be declared as a webservice like:

webservice public static ret_type methodName(params){}

Method can be invoked by javascript as:

var anyVariable = sforce.apex.execute("OrgNameSpace.ClassName","WebserviceMethodName", {param1:paramValue,param2:paramValue,...});

Hope this is helpful.

No comments:

Post a Comment