Apex in AJAX
To invoke Apex through anonymous blocks or public webservice methods, include the following lines in your AJAX code:
<script src="/soap/ajax/64.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/64.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:
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", {});
For more information on the return datatypes, see Data Types in AJAX Toolkit
Use the following line to display a window with debugging information:
sforce.debug.trace=true;