The AJAX toolkit includes built-in support for invoking Apex through anonymous blocks or public webService methods. To do so, include the following lines in your AJAX code:
<script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script> <script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>
global class myClass { webService static Id makeContact(String lastName, Account a) { Contact c = new Contact(LastName = lastName, AccountId = a.Id); return c.id; } }
By using the following JavaScript code:
var account = sforce.sObject("Account"); var id = sforce.apex.execute("myClass","makeContact", {lastName:"Smith", a:account});
The execute method takes primitive data types, sObjects, and lists of primitives or sObjects.
To call a webService method with no parameters, use {} as the third parameter for sforce.apex.execute. For example, to call the following Apex class:
global class myClass{ webService static String getContextUserName() { return UserInfo.getFirstName(); } }
Use the following JavaScript code:
var contextUser = sforce.apex.execute("myClass", "getContextUserName", {});
Both examples result in native JavaScript values that represent the return type of the methods.
Use the following line to display a popup window with debugging information:
sforce.debug.trace=true;