Newer Version Available
Apex in AJAX
To invoke Apex through anonymous blocks or public webservice methods, include the following lines in your AJAX code:
1<script src="/soap/ajax/42.0/connection.js" type="text/javascript"></script>
2<script src="/soap/ajax/42.0/apex.js" type="text/javascript"></script>- Execute anonymously via sforce.apex.executeAnonymous (script). This method returns a result similar to the API's result type, but as a JavaScript structure.
- Use a class WSDL. For example, you can call the following Apex
class:
1global class myClass { 2 webservice static Id makeContact(String lastName, Account a) { 3 Contact c = new Contact(LastName = lastName, AccountId = a.Id); 4 return c.id; 5 } 6}By using the following JavaScript code:
1var account = sforce.sObject("Account"); 2var id = sforce.apex.execute("myClass","makeContact", 3 {lastName:"Smith", 4 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:
1global class myClass{ 2 webservice static String getContextUserName() { 3 return UserInfo.getFirstName(); 4 } 5}Use the following JavaScript code:
1var 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:
1sforce.debug.trace=true;