Salesforce : Invoke Apex with Javascript/AJAX

There is a few situation you may consider to use this solution.

  1. You have a custom button. The custom button needs to call a function in your Apex class.
  2. In your Visualforce page, your Javascript/AJAX code need to invoke an existing Apex function.

 

To achieve this, you need to:

1) Create a Global Apex class with WebService in the function. For example:

 

global class MyApex {
  WebService static void getCurrentTime(String userId) {
    // Your logic goes here...
    ...
    return currentTimeInUserTimezone;
  }
}

 

2) Include AJAX toolkit library in your Javascript

 

{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}


3) Call your Apex function

sforce.apex.execute("MyApex","setCurrentTime", {userId:"{!User.Id}"});

3 simple steps and you are all set to go.

 

A few notes before you implement this:

  • This approach will only work with Professional (with API access) and all the Edition above Professional. If you are creating your custom App, I do not recommend you to include this in your code.
  • This approach will consume API request. Use it with caution.