Saturday 1 December 2012

How to call a method in controller from Javascript


We can call controller's function from javascript with the help of

  1. <apex:actionFunction>

      VF Page:

            <apex:page controller="testClass">

                <apex:form >

                     <apex:actionFunction name="controllerMethod" action="{!check}"/>

                </apex:form>

                 <script>
                      window.onload = function deleteRecord(){

                            controllerMethod(); // this calls the actionFunction defined in the VF page.
                      }

                 </script>

           </apex:page>

        Controller:

        public class testClass{

             public void check(){

                  String s= 'Function called';

                  apexPages.addMessages(s);

             }

        }

    2. JavaSript 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){
                                     //logical operation
                                }
          
                           }
                        },
                        {escape: true}
                    }

                 </script>

           </apex:page>

        Controller:

       Global class testClass{

             @RemoteAction
             Global void check(String name){

                  String s= name;

                  apexPages.addMessages(s);

             }

        }

No comments:

Post a Comment