Friday 25 September 2015

JavaScript Remoting

Javascript Remoting in Salesforce is a functionality which enables a developer to call Controller methods from VF page. This is really helpful in the situation which can't be handled using AJAX or few complex scenarios.

There are basically three things required:
  1. Remote method definition in the controller
  2. Remote method invocation in the JS.
  3. Remote method response handler
Below is a very basic example for JS Remoting:

      VF Page:

            <apex:page controller="testClass">

                 <script>
                   window.onload = function deleteRecord(){
                        var stringName =  'test';
                                                         
                        Visualforce.remoting.Manager.invokeAction('{!$RemoteAction. testClass. check}',                
                         stringName, function(result, event){

                             if (event.status) {

                                 if(result.length > 0){
                                     //do some logic
                                 }
                             }
                              else if(event.type == 'exception'){
                                   alert(event.message + ' '+ event.where);
                              }
                         },
                         {escape: true}                    }

                 </script>

           </apex:page>

        Controller:

       Global class testClass{

             @RemoteAction
             Global void check(String name){

                  String s= name;

                  apexPages.addMessages(s);

             }

        }

Note
  •  If there are multiple parameter required to call a method then pass the parameter in JS method exactly similar which is defined in the controller method. For ex:
          Visualforce.remoting.Manager.invokeAction('{!$RemoteAction. testClass. check}',                
                       stringName,stringName1,stringName2, function(result, event){

No comments:

Post a Comment