calling controller method from javascript salesforce

In salesforce we use java script either in a visualforce page or we execute javascript on custom button (i.e a custom button is override with a java script). While the java script is being executed we may require to call a controller class method which may have a piece of code required for custom functionality. In case of visualforce page we may use action function which can call the controller method from java script directly. You can see following post on action function for more details

For calling a controller method from java script written to override a custom button, we need to use AJAX method callout. In the example below, a custom button on opportunity is overridden with a java script and from the java script calls a method of a controller class.




First two lines of the java script code makes the AJAX toolkit available in the java script of the custom button. As you can see in the code snippet, we have to use method sforce.apex.execute for calling the controller method. We have to just specify the class name in double quotes followed by coma and then method name in double quotes ("className","Methode of that class",{}) We can also call the controller method from Visualforce page using AJAX.  So as to make the AJAX available in visualforce page we have call it as below

<script src="../../soap/ajax/28.0/connection.js" type="text/javascript">
  <!-- AJAX method here -->

Following is the class that is being called from above java script.
/* This is a class for demo purpose, methods of this class are called from  java script
a method without parameter as well as method with parameters is called form java script*/

Public Class updateStatusClass{
 Public updateStatusClass(){
  /*This is a constructor of the demo class*/
 /*Method without any parameters */
 Public void MethodeWithoutParameters(){
  system.debug('**Method without any parameters**');

1 comment:

  1. thanx dude it must be helpful to everyone