Monday 6 February 2012

Call Apex Class method from visualForcePage

Let the apex class is with method as following :-


global class myClass { 
    webService static String myMethod() {     
      return "call to apex method." ; 
   }
}

  And visualForce Page is :- 

<apex:page >
   
 <!--Need this to make connection -->
 <script src="/soap/ajax/15.0/connection.js" type="text/javascript"/>
 <script src="/soap/ajax/15.0/apex.js" type="text/javascript" />

  <script type="text/javascript">
        
       function callApexMethod() {
  //     sforce.debug.trace= true;
         sforce.connection.sessionId = '{!$Api.Session_ID}' ;
         var msg = sforce.apex.execute("myClass","myMethod",{});
         alert(msg); 
           
      }
      
  </script>
  <h1>Congratulations</h1>
  Call apex method from page.
  <apex:form >  
    
      <apex:commandButton value="checkValidations"
onclick="callApexMethod();"/>
    
  </apex:form>  
  
</apex:page>
Result would be an alert 'call to apex method.';