AJAX Toolkit Developer's Guide
AJAX Toolkit Developer's Guide
Table of Contents
Glossary...................................................................................................................................39
Index......................................................................................................................................................51
i
Chapter 1
The AJAX Toolkit
In this chapter ... The AJAX Toolkit is a JavaScript wrapper around the API:
• When to Use the AJAX Toolkit • The AJAX Toolkit is available for any organization that has API access.
• AJAX Toolkit Support Policy • The AJAX Toolkit supports Microsoft Internet Explorer® version 6.0, 7.0,
or 8.0 with the latest hot fixes applied, and Mozilla Firefox version 2.x or 3.x.
• Other Resources
• The AJAX Toolkit is based on the partner WSDL. Because there is no type
• AJAX Typographical Conventions
checking in JavaScript, the type information available in the enterprise WSDL
• Sample Visualforce Page Using the is not needed.
AJAX Toolkit • You can execute any call in the API, and access any API object that you
normally have access to.
• You can issue asynchronous calls, and use callback functions to handle the
results. For more information, see API Calls and the AJAX Toolkit.
• You can use header options with a different syntax than in the API. For more
information, see Using SOAP Header Options with the AJAX Toolkit.
• You can handle errors with the AJAX Toolkit. For more information, see
Error Handling with the AJAX Toolkit.
• The AJAX Toolkit supports relationship queries. See Synchronous Examples
for examples of relationship queries.
Note: Before you use the AJAX Toolkit, you should be familiar with
JavaScript and with the information about the API in the Force.com
Web Services Developer's Guide.
This document explains how to use the AJAX Toolkit in JavaScript to embed
API calls and processes, such as within a Visualforce page..
2
The AJAX Toolkit When to Use the AJAX Toolkit
Other Resources
In addition to the content of this document, there are other resources available for you as you learn to use the AJAX Toolkit:
• Firebug extension to Firefox: Firebug for Firefox
• Eclipse plug-in: Force.com IDE
• Message boards: Developer Force
3
The AJAX Toolkit Sample Visualforce Page Using the AJAX Toolkit
Convention Description
<script src="/soap/ajax/18.0/connection.js" In an example, Courier font indicates items that you should type
type="text/javascript"></script> the information as shown. This includes sample code, literals,
methods, calls, functions, and events from a variety of languages.
sforce.connection.header_option_name="value"; In an example or syntax statement, italics represent variables.
You supply the actual value.
<apex:page >
<script type="text/javascript">
var __sfdcSessionId = '{!GETSESSIONID()}';
</script>
<script src="../../soap/ajax/18.0/connection.js"
type="text/javascript"></script>
<script type="text/javascript"> window.onload = setupPage;
function setupPage() {
//function contains all code to execute after page is rendered
var state = { //state that you need when the callback is called
output : document.getElementById("output"),
startTime : new Date().getTime()};
var callback = {
//call layoutResult if the request is successful
onSuccess: layoutResults,
sforce.connection.query(
"Select Id, Name, Industry From Account order by Industry",
callback);
}
/**
* This method will be called when the toolkit receives a successful
* response from the server.
* @queryResult - result that server returned
* @source - state passed into the query method call.
*/
function layoutResults(queryResult, source) {
if (queryResult.size > 0) {
var output = "";
4
The AJAX Toolkit Sample Visualforce Page Using the AJAX Toolkit
</apex:page>
After creating and navigating to the aboveVisualforce page, you should see text similar to this image:
Note: An easier way to create this page is by using anApex controller. However, the sample is intended to show basic
functionality with the AJAX Toolkit that contains API calls and processes Salesforce.com data.
5
Chapter 2
Working with the AJAX Toolkit
In this chapter ... Most JavaScript that you add to Visualforce pages, buttons, or links has three
sections: first, connecting to the AJAX Toolkit, next, embedding the API methods
• Connecting to the API in JavaScript, and finally, processing the results. This section explains each of
• Embedding API Calls in JavaScript these steps.
• Processing Results
6
Working with the AJAX Toolkit Connecting to the API
<apex:page>
<script src="../../soap/ajax/18.0/connection.js" type="text/javascript"></script>
...
</apex:page>
• For a custom onclick JavaScript button, specify the login call to log into the API:
<body>
{!requireScript("/soap/ajax/18.0/connection.js")}
sforce.connection.login("username", "password");
...
The AJAX Toolkit picks up the endpoint and manages the session ID. You do not need to set them.
The version of the AJAX Toolkit is in the URL.
After this script executes, the toolkit is loaded and a global object, sforce.connection, is created. This object contains all
of the API calls and AJAX Toolkit methods, and manages the session ID. No other session management is needed.
Salesforce.com checks the IP address from which the client application is logging in, and blocks logins from unknown IP
addresses. For a blocked login via the API, Salesforce.com returns a login fault. Then, the user must add their security token
to the end of their password in order to log in. A security token is an automatically-generated key from Salesforce.com. For
example, if a user's password is mypassword, and their security token is XXXXXXXXXX, then the user must enter
mypasswordXXXXXXXXXX to log in. Users can obtain their security token by changing their password or resetting their
security token via the Salesforce.com user interface. When a user changes their password or resets their security token,
Salesforce.com sends a new security token to the email address on the user's Salesforce.com record. The security token is valid
until a user resets their security token, changes their password, or has their password reset. When the security token is invalid,
the user must repeat the login process to log in. To avoid this, the administrator can make sure the client's IP address is added
to the organization's list of trusted IP addresses. For more information, see “Security Token” in the in the Force.com Web
Services API Developer's Guide.
Tip: It is recommended that you obtain your security token via the Salesforce.com user interface from a trusted network
prior to attempting to access Salesforce.com from a new location.
If Single Sign-On (SSO) is enabled for your organization, users who access the API or a desktop client cannot log in to
Salesforce.com unless their IP address is included on your organization's list of trusted IP addresses or on their profile, if their
profile has IP address restrictions set. Futhermore, the delegated authentication authority usually handles login lockout policies
for users with the “Uses Single Sign-On” permission. However, if the security token is enabled for your organization, then
your organization's login lockout settings determine the number of times a user can attempt to log in with an invalid security
token before being locked out of Salesforce.com. For more information, see “Setting Login Restrictions” and “Setting Password
Policies” in the online help.
7
Working with the AJAX Toolkit Embedding API Calls in JavaScript
We recommend that you wrap your JavaScript code so that the entire HTML page is rendered by the browser before the code
executes, to avoid errors. For example:
<body onload="setupPage();">
<div id="output"></div>
</body>
When you specify setupPage() in the body onload, the browser initializes all HTML elements before it calls
setupPage().
For example, the following code could be added to a Visualforce page to retrieve data:
<script type="text/javascript>
function setupPage() {
sforce.connection.query("Select Id, Name, Industry From Account
order by Industry"),
{onSuccess : layoutResults,
onFailure : queryFailed,
source : {
output : document.getElementById("output"),
startTime : new Date().getTime()
}
});
}
</script>
The API interaction in the code above is accomplished in the first line of the setupPage function. A SOQL statement
specifies what data to return. For more information about the source context variable, see The source Context Variable.
After fetching the data in this example, you should handle error conditions, for example:
For more about error handling, see Error Handling with the AJAX Toolkit.
8
Working with the AJAX Toolkit Processing Results
Use a callback function to handle the results of this asynchronous call. A callback function is a function that is passed by
reference to the AJAX Toolkit. The AJAX Toolkit calls the callback function under defined conditions, for example, upon
completion. For more information about callback function syntax, see API Calls and the AJAX Toolkit.
For example, the following code verifies that at least one result was returned, and iterates through the result set if it exists:
/**
* This method will be called when the toolkit receives a successful
* response from the server.
* @queryResult - result that server returned
* @source - state passed into the query method call.
*/
if (queryResult.size > 0) {
var output = "";
A suggested best practice is to use JavaScript onFailure as the callback function for failure conditions and JavaScript
onSuccess for processing results that are successfully returned.
For more information about embedding API calls in JavaScript with the AJAX Toolkit, especially the differences in syntax
and availability of asynchronous calls, see API Calls and the AJAX Toolkit.
Processing Results
You can process the results of a query that returns enough rows to require queryMore and queryLocator, much as you do
now, iterating across the results:
9
Working with the AJAX Toolkit Processing Results
However, the AJAX Toolkit provides the QueryResultIterator object so that you can easily iterate through results without
invoking queryMore and queryLocator. If you are experienced with the API and JavaScript, see QueryResultIterator.
For other calls, you must handle the batching of up to 200 records at a time yourself. For example, the following sample shows
how to batch files for a create() call:
var sb = "";
10
Chapter 3
API Calls and the AJAX Toolkit
In this chapter ... Use the following sections to understand how API calls are used with the AJAX
Toolkit. All calls described in the Force.com Web Services API Developer's
• Synchronous and Asynchronous Calls Guide, plus the runTests call documented in the Force.com Apex Code
with the AJAX Toolkit Developer's Guide.
• API Call Syntax in the AJAX Toolkit
• Object Functions
• Data Types in AJAX Toolkit
• The source Context Variable
• Debugging with the AJAX Toolkit
• Using the Samples
• Synchronous Examples
• Asynchronous Examples
11
API Calls and the AJAX Toolkit Synchronous and Asynchronous Calls with the AJAX Toolkit
sforce.connection.method("arg1","arg2", ...);
For example:
sforce.connection.login("[email protected]","myPassword1");
Asynchronous syntax:
For example:
In this example, onSuccess is the callback function, which will return the results when they are ready.
See Core Calls in the Force.com Web Services API Developer's Guide for call usage, arguments, and best practices, but use the
AJAX Toolkit syntax for methods you embed in JavaScript.
Note: Because delete is a JavaScript keyword, use deleteIds instead of the API call delete.
Object Functions
Property values can be accessed directly or by using a generic set or get method:
• A get function for each field in the object. For example, an Account object has a get("Name") function. This can be
used instead of object.Field (for example, account.Name).
• A set function for each field in the object. For example, an Account object has a set("Name) function. This can be used
instead of object.Field = value.
For example, you can get the value of the Name field from an Account using either of these methods:
12
API Calls and the AJAX Toolkit Data Types in AJAX Toolkit
• account.get("Name")
• account.Name
• account["Name"]
You can set the value of the Name field from an Account using either of these methods:
• account.set("Name", "MyAccount");
• account.Name = "MyAccount";
• account["Name"]="MyAccount";
sforce.debug.log(myVar);
You can open the debugging window at any point by using this command:
sforce.debug.open();
13
API Calls and the AJAX Toolkit Using the Samples
sforce.debug.log(myVar);
The AJAX Toolkit samples in the following sections use log(). To use the samples in the following sections, add this simple
version of the log code before the first use of log:
function log(message) {
alert(message);
}
Synchronous Examples
The following examples are synchronous calls. No callback methods are required.
try{
var result = sforce.connection.login("[email protected]", "password");
log("logged in with session id " + result.sessionId);
}catch(error) {
if (error.faultcode.indexOf("INVALID_LOGIN") != -1) {
log("check your username and passwd, invalid login");
} else {
log(error);
}
}
query Example:
queryMore Example:
14
API Calls and the AJAX Toolkit Synchronous Examples
log(records.length);
log(sb.toString());
if (result.getBoolean("done")) {
queryMore = false;
} else {
result = sforce.connection.queryMore(result.queryLocator);
}
}
queryAll Example:
while(it.hasNext()) {
var record = it.next();
var accountName = record.Account ? record.Account.Name : null;
Note: Relationship name formats differ depending on the direction of the relationship (parent-to-child or
child-to-parent), and also depending on whether the objects are standard or custom objects. For more information,
see Relationship Queries in the Force.com Web Services API Developer's Guide.
while(ait.hasNext()) {
var account = ait.next();
15
API Calls and the AJAX Toolkit Synchronous Examples
if (account.Contacts) {
var cit = new sforce.QueryResultIterator(account.Contacts);
while(cit.hasNext()) {
var contact = cit.next();
contacts.push(contact.LastName);
}
}
create Example:
if (result[0].getBoolean("success")) {
log("new account created with id " + result[0].id);
} else {
log("failed to create account " + result[0]);
}
delete Example:
if (result[0].getBoolean("success")) {
log("new account created with id " + result[0].id);
account.Id = result[0].id;
} else {
throw ("failed to create account " + result[0]);
}
16
API Calls and the AJAX Toolkit Synchronous Examples
merge Example:
account1.id = result[0].id;
account2.id = result[1].id;
//call merge
result = sforce.connection.merge([request]);
if (result[0].getBoolean("success")) {
log("merge success " + result[0]);
} else {
log("merge failed " + result[0]);
}
process Example:
if(!processRes[0].getBoolean('success')){
log("The first process request failed and it should not have");
}
if(processRes[1].getBoolean('success')){
log("The second process request succeeded and it should not have");
}
log(processRes[0].errors);
log(processRes[1].errors);
update Example:
//create an account
var account = new sforce.SObject("Account");
account.Name = "myName";
account.Phone = "2837484894";
17
API Calls and the AJAX Toolkit Synchronous Examples
result = sforce.connection.create([account]);
if (result[0].getBoolean("success")) {
log("account with id " + result[0].id + " updated");
} else {
log("failed to update account " + result[0]);
}
undelete Example:
result = sforce.connection.deleteIds([account.id]);
if (!result[0].getBoolean("success")) throw "delete failed";
log("account deleted " + result);
result = sforce.connection.undelete([account.id]);
if (!result[0].getBoolean("success")) throw "undelete failed";
log("account undeleted " + result[0]);
upsert Example:
account.Id = result[0].id;
account.Name = "TestingAjaxUpsert2";
// this will update the account
result = sforce.connection.upsert("Id", [account]);
retrieve Example:
result[0].Phone = "111111111111";
18
API Calls and the AJAX Toolkit Synchronous Examples
result = sforce.connection.update(result);
if (result[0].getBoolean("success") == false) throw "update failed";
log("account updated: " + result[0]);
search Example:
if (result) {
var records = result.getArray("searchRecords");
getDeleted Example:
getUpdated Example:
convertLead Example:
19
API Calls and the AJAX Toolkit Synchronous Examples
lead.Company = account.Name;
result = sforce.connection.create([lead]);
lead.Id = result[0].id;
result = sforce.connection.convertLead([convert]);
if (result[0].getBoolean("success")) {
log("lead converted " + result[0]);
} else {
log("lead convert failed " + result[0]);
}
Describe Examples
describeSObject Account Example:
describeSObjects Example:
describeGlobal Example:
20
API Calls and the AJAX Toolkit Synchronous Examples
describeLayout Example:
function detailLayoutSections(sections) {
for (var i=0; i<sections.length; i++) {
var section = sections[i];
log(section.columns + ":" + section.heading + ":");
layoutRows(section.getArray("layoutRows"));
}
}
function layoutRows(rows) {
for (var i=0; i<rows.length; i++) {
var row = rows[i];
layoutItems(row.getArray("layoutItems"));
}
}
function layoutItems(items) {
for (var i=0; i<items.length; i++) {
var item = items[i];
log(" " + item.label);
}
}
describeTabs Example:
function displayTabs(tabs) {
for( var i=0; i<tabs.length; i++) {
var tab = tabs[i];
log( " " + tab.label + " " + tab.url);
}
}
Utility Examples
getServerTimestamp Example:
getUserInfo
21
API Calls and the AJAX Toolkit Synchronous Examples
sforce.connection.resetPassword(id);
sforce.connection.setPassword(id, "123456");
sendEmail Example:
The following sample shows best practice techniques by putting all processing in a function that does not execute until the
HTML page is loaded.
<html>
<head>
<script src="/soap/ajax/18.0/connection.js"></script>
<script>
var contactId = "{!Contact_ID}";
function initPage() {
try{
var contact = sforce.connection.retrieve("AccountId", "Contact", [contactId])[0];
var accountsRetrieved = sforce.connection.retrieve("Id, Name, Industry,
LastModifiedDate", "Account", [contact.AccountId]);
if (accountsRetrieved.length > 0) {
var account = accountsRetrieved.records[0];
document.body.innerHTML += "Account name: <a href='/" + account.Id;
document.body.innerHTML += "' target='_blank'>" + account.Name + "</a><br>;
document.body.innerHTML += "Industry: " + account.Industry + "<br>";
}
} catch (e) {
document.body.innerHTML += "Error retrieving contact information";
document.body.innerHTML += "<br>Fault code: " + e.faultcode;
document.body.innerHTML += "<br>Fault string: " + e.faultstring;
}
}
</script>
</head>
<body onload="initPage();">
22
API Calls and the AJAX Toolkit Asynchronous Examples
</body>
</html>
Asynchronous Examples
The following examples are asynchronous calls. These samples use callback methods to the API call.
query Example:
function success(result) {
var records = result.getArray("records");
function failure(error) {
log("An error has occurred " + error);
}
function success(result) {
var it = new sforce.QueryResultIterator(result);
while(it.hasNext()){
var record = it.next();
log(record.Name + " -- " + record.Id);
}
}
function failure(error) {
23
API Calls and the AJAX Toolkit Asynchronous Examples
queryResultIterator Example:
function success(result) {
var it = new sforce.QueryResultIterator(result);
while(it.hasNext()){
var record = it.next();
log(record.Name + " -- " + record.Id);
}
}
function failure(error) {
log("An error has occurred " + error);
}
queryMore Example:
function success(result) {
var records = result.getArray("records");
log(records.length);
log(sb.toString());
if (result.queryLocator) {
sforce.connection.queryMore(result.queryLocator, {
onSuccess : success, onFailure : log});
}
}
create Example:
sforce.connection.create([account],
{onSuccess : success, onFailure : failed});
function success(result) {
if (result[0].getBoolean("success")) {
log("new account created with id " + result[0].id);
} else {
log("failed to create account " + result[0]);
}
}
function failed(error) {
log("An error has occurred " + error);
}
24
API Calls and the AJAX Toolkit Asynchronous Examples
sforce.connection.create([campaign ],
{onSuccess : success, onFailure : log});
function success(result) {
if (result[0].getBoolean("success")) {
log("new campaign created with id " + result[0].id);
} else {
log("failed to create campaign " + result[0]);
}
}
var callback = {
onSuccess: function(result) {
if (result[0] == null) throw "retrive failed";
log("account retrieved: " + result[0]);
},
onFailure: function(error) {
log("failed due to " + error);
}
};
25
Chapter 4
Using SOAP Header Options with the AJAX Toolkit
All header options in the API are supported in the toolkit, but they are specified differently than in the API. Use the following
syntax for specifying header options:
• For headers that have only one option such as CallOptions and QueryOptions:
sforce.connection.header_option_name="value";
• For headers that have more than one option such as AssignmentRuleHeader:
sforce.connection.header_name = {}
sforce.connection.header_name.header_option_name="value";
The following table lists each valid option and a description (and the corresponding SOAP header name in the API for your
reference).
• From the AssignmentRuleHeader:
assignmentRuleId
ID of a specific assignment rule to run for the case or lead. Can be an inactive assignment rule. The ID can be retrieved
by querying the AssignmentRule object. If specified, do not specify useDefaultRule. This element is ignored for
accounts, because all territory assignment rules are applied. If the value is not in correct ID format (15-character or
18-character Salesforce.com ID), the call fails and a MALFORMED_ID exception is returned.
useDefaultRule
If true for a Case or Lead, uses the default (active) assignment rule for a Case or Lead. If specified, do not specify an
assignmentRuleId. If true for an account, all territory assignment rules are applied, and if false, no territory
assignment rules are applied.
• From CallOptions:
client
A string that identifies a particular client.
defaultNamespace
A string that identifies a developer namespace prefix.
• From EmailHeader:
triggerAutoResponseEmail
Indicates whether to trigger auto-response rules (true) or not (false), for leads and cases. In the Salesforce.com
user interface, this email can be automatically triggered by a number of events, for example resetting a user password.
26
Using SOAP Header Options with the AJAX Toolkit
triggerOtherEmail
Indicates whether to trigger email outside the organization (true) or not (false). In the Salesforce.com user interface,
this email can be automatically triggered by creating, editing, or deleting a contact for a case.
triggerUserEmail
Indicates whether to trigger email that is sent to users in the organization (true) or not (false). In the Salesforce.com
user interface, this email can be automatically triggered by a number of events; resetting a password, creating a new
user, adding comments to a case, or creating or modifying a task.
• From LoginScopeHeader:
organizationId
The ID of the organization against which you will authenticate Self-Service users.
portalId
Specify only if user is a Customer Portal user. The ID of the portal for this organization. The ID is available in the
Salesforce.com user interface:
- Select Setup ➤ Customize ➤ Customer Portal ➤ Settings
- Select a Customer Portal name, and on the Customer Portal detail page, the URL of the Customer Portal displays.
The Portal ID is in the URL.
• From MruHeader:
updateMru
Indicates whether to update the list of most recently used items (true) or not (false). For retrieve, if the result has
only one row, MRU is updated to the ID of the retrieve result. For query, if the result has only one row and the ID
field is selected, the MRU is updated to the ID of the query result.
• From QueryOptions:
batchSize
Batch size for the number of records returned in a query or queryMore call. Child objects count toward the number
of records for the batch size. For example, in relationship queries, multiple child objects may be returned per parent
row returned. The default is 500; the minimum is 200, and the maximum is 2,000.
• From SessionHeader:
sessionId
Session ID returned by the login call to be used for subsequent call authentication. Since session management is done
for you by the AJAX Toolkit, most scripts won't need to use this header option.
• From UserTerritoryDeleteHeader:
transferToUserId
The ID of the user to whom open opportunities in that user's territory will be assigned when an opportunity's owner
(user) is removed from a territory.
For more information about SOAP headers in the API, see the Force.com Web Services Developer's Guide.
27
Chapter 5
Error Handling with the AJAX Toolkit
The AJAX Toolkit provides the ability to handle errors for synchronous and asynchronous calls:
<html>
<head>
<script src="/soap/ajax/18.0/connection.js" type="text/javascript"></script>
<script>
function setupPage() {
var output = document.getElementById("output");
var startTime = new Date().getTime()
try {
var queryResult = sforce.connection.query("Select Id, Name, Industry From
Account order by Industry limit 30");
layoutResults(queryResult, output, startTime);
} catch(error) {
queryFailed(error, output);
}
}
if (queryResult.size > 0) {
var output = "";
var records = queryResult.getArray('records');
out.innerHTML = output + "<BR> query complexted in: " + timeTaken + " ms.";
} else {
out.innerHTML = "No records matched.";
}
}
</script>
</head>
28
Error Handling with the AJAX Toolkit
<body onload="setupPage()">
<div id="output"></div>
</body>
</html>
function displayResult(result){}
function queryFailed(error){}
If the onFailure property was not defined, the AJAX Toolkit pops up a new read-only browser window showing the error.
29
Chapter 6
Advanced Topics
This chapter contains information about advanced activities in the AJAX Toolkit.
QueryResultIterator
The AJAX Toolkit provides the QueryResultIterator object so that you can easily iterate through results without invoking
queryMore and queryLocator.
You can use the QueryResultIterator object and functions to iterate over query results returned by the AJAX Toolkit:
while (it.hasNext()) {
var account = it.next();
sforce.debug.log(account.Name);
}
But if you are using the AJAX Toolkit, you need to escape the single quote literal character twice:
30
Advanced Topics Working with Base64 Binary Encoded Strings
<html>
<head>
<script type="text/javascript" src="/js/dojo/0.3.1/dojo.js"></script>
<script src="/soap/ajax/18.0/connection.js"></script>
<script>
function setup() {
var document_ta = document.getElementById("document-ta");
if (records.length == 1) {
dojo.io.bind({
url: "/servlet/servlet.FileDownload?file=" + records[0].Id,
load: loadDocument});
} else {
doc_ta.value = "no records found";
}
}
</script>
</head>
<body onload="setup()">
<textarea id="document-ta" cols="80" rows="20">
</textarea>
</body>
</html>
Note: This example uses the JavaScript toolkit Dojo. For more information, see http://dojotoolkit.org/
31
Advanced Topics Using the Timeout Parameter with Asynchronous Calls
Values for this parameter are in milliseconds, and valid values are integers beginning with 1.
If the call is successful within the time specified by the callout, no additional actions are taken. If the call is not successful, the
onFailure action is performed.
Caution: Use this parameter with caution. Because the timeout is performed on the client side, it is possible that
the call may complete on the server but the timeout is still triggered. For example, you might issue a create call to
create 100 new accounts, and any number of them, 1 or 100, might be created just before the timeout is triggered;
your onFailure action would still occur, but the accounts would have been created.
AJAX Proxy
Some browsers don't allow JavaScript code to connect to external servers directly. Therefore, you may need to send requests
through the AJAX proxy.
Note: To use the AJAX proxy, you must register all external services in the Salesforce.com user interface, in Setup
➤ Security Controls ➤ Remote Site Settings.
For security reasons, Salesforce.com restricts the outbound ports you may specify to one of the following:
• 80: This port only accepts HTTP connections.
• 443: This port only accepts HTTPS connections.
• 7000-10000 (inclusive): These ports accept HTTP or HTTPS connections.
The AJAX proxy is part of the AJAX Toolkit. Access it using remoteFunction defined in connection.js. You can
specify any HTTP method in remoteFucntion, for example HTTP GET or POST, and it will be forwarded to the external
service.
The following examples illustrate typical approaches for GET and POST:
GET Example:
sforce.connection.remoteFunction({
url : "http://www.myExternalServer.com",
onSuccess : function(response) {
alert("result" + response);
}
});
POST Example:
32
Advanced Topics remoteFunction Syntax and Parameters
url : "http://services.xmethods.net:80/soap",
requestHeaders: {"Content-Type":"text/xml",
"SOAPAction": "\"\""
},
requestData: envelope,
method: "POST",
onSuccess : function(response) {
sforce.debug.log(response);
},
onFailure : function(response) {
alert("Failed" + response)
}
});
sforce.connection.remoteFunction({
url : endpoint_url,
onSuccess : callback_method
onFailure : error_callback
method : http_method
mimeType : "text/plain" | "text/xml"
async : true | false
requestHeaders : http_headers
requestData : http_post_data
cache : true | false
timeout : client_side_timeout_in_ms
Note: cache and timeout are available in version 10.0 and later.
33
Advanced Topics Downloading the Salesforce.com Client Certificate
4. Any remaining intermediate certificates. Do not include the root certificate authority certificate. The root certificate
is not sent by your server. Salesforce.com already has its own list of trusted certificates on file, and a certificate in
the chain must be signed by one of those root certificate authority certificates.
34
Chapter 7
Migrating from the Beta AJAX Toolkit
If you have developed applications using the Beta version of the AJAX Toolkit, your application will continue to function. We
recommend that you upgrade to the current version in order to obtain all the features available. Only the current version is
actively supported.
The following changes are required when you upgrade from Beta to the current version:
Toolkit location
Beta Value:
https://www.salesforce.com/services/lib/ajax/beta3.3/sforceclient.js
Remove for all versions after Beta. The AJAX Toolkit handles all session management once you log in.
Root variable
Beta Value:
sforceClient
Entity object
Beta Value:
DynaBean
DynaBean.getDefinition()
Beta Value:
DynaBean.GetDefinition()
Loop through fields returned by the appropriate describe call to see what is present.
35
Migrating from the Beta AJAX Toolkit
getName()
Beta Value:
getName()
This returned the name of the dynabean.
Change to this value:
sforce.SObject.type
Web methods
Beta value starts with a capital letter:
sforceClient.GetUserInfo();
Sforce.Util
Beta Value:
Sforce.Util
Use your own utilities for date formatting and other tasks.
36
Migrating from the Beta AJAX Toolkit
Callback
Beta syntax:
37
Migrating from the Beta AJAX Toolkit
function layoutResults(queryResult) {
//success
}
function queryFailed(error) {
//error
}
Exception handling
Beta syntax:
try {
var saveResult = sforce.connection.update([contact]);
}catch(error) {
sforce.debug.log(error.faultcode);
sforce.debug.log(error.faultstring);
}
38
Glossary
A |B |C |D |E |F |G |H |I |J |K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z
A
AJAX Toolkit
A JavaScript wrapper around the API that allows you to execute any API call and access any object you have permission
to view from within JavaScript code. For more information, see the AJAX Toolkit Developer's Guide.
Apex
Force.com Apex code is a strongly-typed, object-oriented programming language that allows developers to execute flow
and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API.
Using syntax that looks like Java and acts like database stored procedures, Apex code enables developers to add business
logic to most system events, including button clicks, related record updates, and Visualforce pages. Apex scripts can be
initiated by Web service requests and from triggers on objects.
B
Boolean Operators
You can use Boolean operators in report filters to specify the logical relationship between two values. For example, the
AND operator between two values yields search results that include both values. Likewise, the OR operator between two
values yields search results that include either value.
C
Callout, Apex
An Apex callout enables you to tightly integrate your Apex with an external service by making a call to an external Web
service or sending a HTTP request from an Apex script and then receiving the response.
Child Relationship
A relationship that has been defined on an sObject that references another sObject as the “one” side of a one-to-many
relationship. For example, contacts, opportunities, and tasks have child relationships with accounts.
See also sObject.
39
Glossary
Class, Apex
A template or blueprint from which Apex objects are created. Classes consist of other classes, user-defined methods,
variables, exception types, and static initialization code. In most cases, Apex classes are modeled on their counterparts in
Java.
Component, Visualforce
Something that can be added to a Visualforce page with a set of tags, for example, <apex:detail>. Visualforce includes
a number of standard components, or you can create your own custom components.
Controller, Visualforce
An Apex class that provides a Visualforce page with the data and business logic it needs to run. Visualforce pages can use
the standard controllers that come by default with every standard or custom object, or they can use custom controllers.
Custom Field
A field that can be added in addition to the standard fields to customize Salesforce.com for your organization’s needs.
Custom Help
Custom text administrators create to provide users with on-screen information specific to a standard field, custom field,
or custom object.
Custom Links
Custom URLs defined by administrators to integrate your Salesforce.com data with external websites and back-office
systems. Formerly known as Web links.
Custom Object
Custom records that allow you to store information unique to your organization.
Custom S-Control
Custom Web content for use in custom links. Custom s-controls can contain any type of content that you can display in
a browser, for example a Java applet, an Active-X control, an Excel file, or a custom HTML Web form.
D
Data Loader
A Force.com platform tool used to import and export data from your Salesforce.com organization.
Date Literal
A keyword in a SOQL or SOSL query that represents a relative range of time such as last month or next year.
Delegated Authentication
A security process where an external authority is used to authenticate Force.com platform users.
Developer Edition
A free, fully-functional Salesforce.com organization designed for developers to extend, integrate, and develop with the
Force.com platform. Developer Edition accounts are available on developer.force.com.
40
Glossary
Developer Force
The Developer Force website at developer.force.com provides a full range of resources for platform developers, including
sample code, toolkits, an online developer community, and the ability to obtain limited Force.com platform environments.
Document Library
A place to store documents without attaching them to accounts, contacts, opportunities, or other records.
E
Email Alert
Email alerts are workflow and approval actions that are generated using an email template by a workflow rule or approval
process and sent to designated recipients, either Salesforce.com users or others.
Email Template
A form email that communicates a standard message, such as a welcome letter to new employees or an acknowledgement
that a customer service request has been received. Email templates can be personalized with merge fields, and can be
written in text, HTML, or custom format.
Enterprise Edition
A Salesforce.com edition designed for larger, more complex businesses.
Enterprise WSDL
A strongly-typed WSDL for customers who want to build an integration with their Salesforce.com organization only, or
for partners who are using tools like Tibco or webMethods to build integrations that require strong typecasting. The
downside of the Enterprise WSDL is that it only works with the schema of a single Salesforce.com organization because
it is bound to all of the unique objects and fields that exist in that organization's data model.
F
Field
A part of an object that holds a specific piece of information, such as a text or currency value.
Field-Level Security
Settings that determine whether fields are hidden, visible, read only, or editable for users based on their profiles. Available
in Enterprise, Unlimited, and Developer Editions only.
Force.com
The salesforce.com platform for building applications in the cloud. Force.com combines a powerful user interface, operating
system, and database to allow you to customize and deploy applications in the cloud for your entire enterprise.
Foreign key
A field whose value is the same as the primary key of another table. You can think of a foreign key as a copy of a primary
key from another table. A relationship is made between two tables by matching the values of the foreign key in one table
with the values of the primary key in another.
41
Glossary
Formula Field
A type of custom field. Formula fields automatically calculate their values based on the values of merge fields, expressions,
or other values.
Function
Built-in formulas that you can customize with input parameters. For example, the DATE function creates a date field
type from a given year, month, and day.
G
Gregorian Year
A calendar based on a twelve month structure used throughout much of the world.
Group Edition
A product designed for small businesses and workgroups with a limited number of users.
H
HTTP Debugger
An application that can be used to identify and inspect SOAP requests that are sent from the AJAX Toolkit. They behave
as proxy servers running on your local machine and allow you to inspect and author individual requests.
I
ID
See Salesforce.com Record ID.
Inline S-Control
An s-control that displays within a record detail page or dashboard, rather than on its own page.
Instance
The cluster of software and hardware represented as a single logical server that hosts an organization's data and runs their
applications. The Force.com platform runs on multiple instances, but data for any single organization is always consolidated
on a single instance.
Integration User
A Salesforce.com user defined solely for client apps or integrations. Also referred to as the logged-in user in a Force.com
Web Services API context.
ISO Code
The International Organization for Standardization country code, which represents each country by two letters.
J
Junction Object
A custom object with two master-detail relationships. Using a custom junction object, you can model a “many-to-many”
relationship between two objects. For example, you may have a custom object called “Bug” that relates to the standard
case object such that a bug could be related to multiple cases and a case could also be related to multiple bugs.
K
No Glossary items for this entry.
42
Glossary
L
License Management Application (LMA)
A free AppExchange app that allows you to track sales leads and accounts for every user who downloads a managed package
of yours from AppExchange.
Logged-in User
In a Force.com Web Services API context, the username used to log into Salesforce.com. Client applications run with
the permissions and sharing of the logged-in user. Also referred to as an integration user.
M
Manual Sharing
Record-level access rules that allow record owners to give read and edit permissions to other users who might not have
access to the record any other way.
Many-to-Many Relationship
A relationship where each side of the relationship can have many children on the other side. Many-to-many relationships
are implemented through the use of junction objects.
Master-Detail Relationship
A relationship between two different types of records that associates the records with each other. For example, accounts
have a master-detail relationship with opportunities. This type of relationship affects record deletion, security, and makes
the lookup relationship field required on the page layout.
Metadata
Information about the structure, appearance, and functionality of an organization and any of its parts. Force.com uses
XML to describe metadata.
Metadata WSDL
A WSDL for users who want to use the Force.com Metadata API calls.
Multitenancy
An application model where all users and apps share a single, common infrastructure and code base.
N
Namespace
In a packaging context, a one- to 15-character alphanumeric identifier that distinguishes your package and its contents
from packages of other developers onAppExchange, similar to a domain name. Salesforce.com automatically prepends
your namespace prefix, followed by two underscores (“__”), to all unique component names in your Salesforce.com
organization.
43
Glossary
O
Object
An object allows you to store information in your Salesforce.com organization. The object is the overall definition of the
type of information you are storing. For example, the case object allow you to store information regarding customer
inquiries. For each object, your organization will have multiple records that store the information about specific instances
of that type of data. For example, you might have a case record to store the information about Joe Smith's training inquiry
and another case record to store the information about Mary Johnson's configuration issue.
Object-Level Help
Custom help text that you can provide for any custom object. It displays on custom object record home (overview), detail,
and edit pages, as well as list views and related lists.
Object-Level Security
Settings that allow an administrator to hide whole tabs and objects from a user so that he or she does not know that type
of data exists. On the platform you set object-level access rules with object permissions on user profiles.
One-to-Many Relationship
A relationship in which a single object is related to many other objects. For example, an account may have one or more
related contacts.
Organization-Wide Defaults
Settings that allow you to specify the baseline level of data access that a user has in your organization. For example, you
can make it so that any user can see any record of a particular object that is enabled in their user profile, but that they need
extra permissions to edit one.
Outbound Call
Any call that originates from a user to a number outside of a call center in Salesforce CRM Call Center.
Outbound Message
Workflow, approval, or milestone actions that send the information you specify to an endpoint you designate, such as an
external service. An outbound message sends the data in the specified fields in the form of a SOAP message to the endpoint.
Outbound messaging is configured in the Salesforce.com setup menu. Then you must configure the external endpoint.
You can create a listener for the messages using the Force.com Web Services API.
Overlay
An overlay displays additional information when you hover your mouse over certain user interface elements. Depending
on the overlay, it will close when you move your mouse away, click outside of the overlay, or click a close button.
Owner
Individual user to which a record (for example, a contact or case) is assigned.
P
Parent Account
Organization or company that an account is affiliated with or owned by. By specifying a parent for an account, you can
get a global view of all parent/subsidiary relationships using the View Hierarchy link.
Partner WSDL
A loosely-typed WSDL for customers, partners, and ISVs who want to build an integration or an AppExchange app that
can work across multiple Salesforce.com organizations. With this WSDL, the developer is responsible for marshaling
data in the correct object representation, which typically involves editing the XML. However, the developer is also freed
44
Glossary
from being dependent on any particular data model or Salesforce.com organization. Contrast this with the Enterprise
WSDL, which is strongly typed.
Personal Edition
Product designed for individual sales representatives and single users.
Platform Edition
A Salesforce.com edition based on either Enterprise Edition or Unlimited Edition that does not include any of the standard
Salesforce.com CRM apps, such as Sales or Service & Support.
Primary Key
A relational database concept. Each table in a relational database has a field in which the data value uniquely identifies
the record. This field is called the primary key. The relationship is made between two tables by matching the values of
the foreign key in one table with the values of the primary key in another.
Production Organization
A Salesforce.com organization that has live users accessing data.
Professional Edition
A Salesforce.com edition designed for businesses who need full-featured CRM functionality.
Q
Queue
A holding area for items before they are processed. Salesforce.com uses queues in a number of different features and
technologies.
Query Locator
A parameter returned from the query() or queryMore() API call that specifies the index of the last result record that
was returned.
http://na1.salesforce.com/001/e?name=value
R
Record
A single instance of a Salesforce.com object. For example, “John Jones” might be the name of a contact record.
Record Name
A standard field on all Salesforce.com objects. Whenever a record name is displayed in a Force.com application, the value
is represented as a link to a detail view of the record. A record name can be either free-form text or an autonumber field.
Record Name does not have to be a unique value.
Record Type
A field available for certain records that can include some or all of the standard and custom picklist values for that record.
Record types are special fields that you can associate with profiles to make only the included picklist values available to
users with that profile.
45
Glossary
Record-Level Security
A method of controlling data in which you can allow a particular user to view and edit an object, but then restrict the
records that the user is allowed to see.
Recycle Bin
A page that lets you view and restore deleted information. Access the Recycle Bin by using the link in the sidebar.
Related Object
Objects chosen by an administrator to display in the console's mini view when records of a particular type are shown in
the console's detail view. For example, when a case is in the detail view, an administrator can choose to display an associated
account, contact, or asset in the mini view.
Relationship
A connection between two objects, used to create related lists in page layouts and detail levels in reports. Matching values
in a specified field in both objects are used to link related data; for example, if one object stores data about companies and
another object stores data about people, a relationship allows you to find out which people work at the company.
Relationship Query
In a SOQL context, a query that traverses the relationships between objects to identify and return results. Parent-to-child
and child-to-parent syntax differs in SOQL queries.
Report Types
Specifies the objects and fields that can be used as the basis of a report. In addition to pre-defined standard report types,
you can create custom report types for more advanced reporting requirements.
Role Hierarchy
A record-level security setting that defines different levels of users such that users at higher levels can view and edit
information owned by or shared with users beneath them in the role hierarchy, regardless of the organization-wide sharing
model settings.
Running User
The user whose security settings determine what data is displayed in a dashboard. Because only one running user is specified
per dashboard, everyone who can access the dashboard sees the same data, regardless of their personal security settings.
S
SaaS
See Software as a Service (SaaS).
Sandbox Organization
A nearly identical copy of a Salesforce.com production organization. You can create multiple sandboxes in separate
environments for a variety of purposes, such as testing and training, without compromising the data and applications in
your production environment.
46
Glossary
Session ID
An authentication token that is returned when a user successfully logs in to Salesforce.com. The Session ID prevents a
user from having to log in again every time he or she wants to perform another action in Salesforce.com. Different from
a record ID or Salesforce.com ID, which are terms for the unique ID of a Salesforce.com record.
Session Timeout
The period of time after login before a user is automatically logged out. Sessions expire automatically after a predetermined
length of inactivity, which can be configured in Salesforce.com by clicking Setup ➤ Security Controls. The default is
120 minutes (two hours). The inactivity timer is reset to zero if a user takes an action in the Web interface or makes an
API call.
Setup
An administration area where you can customize and define Force.com applications. Access Setup through the Setup link
at the top of Salesforce.com pages.
Sharing
Allowing other users to view or edit information you own. There are different ways to share data:
• Sharing Model—defines the default organization-wide access levels that users have to each other’s information and
whether to use the hierarchies when determining access to data.
• Role Hierarchy—defines different levels of users such that users at higher levels can view and edit information owned
by or shared with users beneath them in the role hierarchy, regardless of the organization-wide sharing model settings.
• Sharing Rules—allow an administrator to specify that all information created by users within a given group or role is
automatically shared to the members of another group or role.
• Manual Sharing—allows individual users to share a specific account or opportunity with other users or groups.
• Apex-Managed Sharing—enables developers to programmatically manipulate sharing to support their application’s
behavior. See Apex-Managed Sharing.
Sharing Model
Behavior defined by your administrator that determines default access by users to different types of records.
Sharing Rule
Type of default sharing created by administrators. Allows users in a specified group or role to have access to all information
created by users within a given group or role.
Sites
Force.com sites enables you to create public websites and applications that are directly integrated with your Salesforce.com
organization—without requiring users to log in with a username and password.
47
Glossary
Standard Object
A built-in object included with the Force.com platform. You can also build custom objects to store information that is
unique to your app.
Syndication Feeds
Give users the ability to subscribe to changes within Force.com sites and receive updates in external news readers.
System Log
A separate window console that can be used for debugging code snippets. Enter the code you want to test at the bottom
of the window and click Execute. The body of the System Log displays system resource information, such as how long a
line took to execute or how many database calls were made. If the code did not run to completion, the console also displays
debugging information.
T
Test Method
An Apex class method that verifies whether a particular piece of code is working properly. Test methods take no arguments,
commit no data to the database, and can be executed by the runTests() system method either through the command
line or in an Apex IDE, such as the Force.com IDE.
Translation Workbench
Administration setup area where your users can translate custom field names, picklist values, record types, and page layout
sections. The translation workbench also determines which users translate different languages.
Trigger
A piece of Apex that executes before or after records of a particular type are inserted, updated, or deleted from the database.
Every trigger runs with a set of context variables that provide access to the records that caused the trigger to fire, and all
triggers run in bulk mode—that is, they process several records at once, rather than just one record at a time.
U
Unit Test
A unit is the smallest testable part of an application, usually a method. A unit test operates on that piece of code to make
sure it works correctly. See also Test Method.
Unlimited Edition
Unlimited Edition is salesforce.com's flagship solution for maximizing CRM success and extending that success across
the entire enterprise through the Force.com platform.
V
Validation Rule
A rule that prevents a record from being saved if it does not meet the standards that are specified.
48
Glossary
Visualforce
A simple, tag-based markup language that allows developers to easily define custom pages and components for apps built
on the platform. Each tag corresponds to a coarse or fine-grained component, such as a section of a page, a related list,
or a field. The components can either be controlled by the same logic that is used in standard Salesforce.com pages, or
developers can associate their own logic with a controller written in Apex.
W
Web Service
A mechanism by which two applications can easily exchange data over the Internet, even if they run on different platforms,
are written in different languages, or are geographically remote from each other.
WebService Method
An Apex class method or variable that can be used by external systems, such as an s-control or mash-up with a third-party
application. Web service methods must be defined in a global class.
Workflow Action
An email alert, field update, outbound message, or task that fires when the conditions of a workflow rule are met.
Workflow Queue
A list of workflow actions that are scheduled to fire based on workflow rules that have one or more time-dependent
workflow actions.
Workflow Rule
A workflow rule sets workflow actions into motion when its designated conditions are met. You can configure workflow
actions to execute immediately when a record meets the conditions in your workflow rule, or set time triggers that execute
the workflow actions on a specific day.
Workflow Task
A workflow action that assigns a task to an application user when a workflow rule is triggered.
Wrapper Class
A class that abstracts common functions such as logging in, managing sessions, and querying and batching records. A
wrapper class makes an integration more straightforward to develop and maintain, keeps program logic in one place, and
affords easy reuse across components. Examples of wrapper classes in Salesforce.com include theAJAX Toolkit, which is
a JavaScript wrapper around the Salesforce.com Web Services API, wrapper classes such as CCritical Section in the
CTI Adapter for Salesforce CRM Call Center, or wrapper classes created as part of a client integration application that
accesses Salesforce.com using the Force.com Web Services API.
49
Glossary
X
No Glossary items for this entry.
Y
No Glossary items for this entry.
Z
No Glossary items for this entry.
50
Index
Index
A L
Advanced topics 30 log method 13
AJAX proxy 32
API calls, see Calls 11
assignmentRuleID header option 26
M
Asynchronous calls Migrating from previous versions 35
error handling 28
introduction 11
samples 23 O
using the timeout parameter 32
Object functions 12
onclick JavaScript button 7
B organizationId header option 26
Other resources 3
Base64 binary encoded strings 31 Outbound port restrictions 32
batchSize header option 26
Beta version, migrating from 35
P
C Port restrictions 32
Processing results 9
callback function Proxy for AJAX 32
and API calls 11
defined 2
in sample s-control 4 Q
Calls
API with AJAX Toolkit 11 queryLocator, see QueryResultIterator 30
different syntax with AJAX Toolkit 12 queryMore, see QueryResultIterator 30
Client certificate download 33 QueryResultIterator 30
client header option 26
Connecting to AJAX Toolkit 7 R
connection.js 7
Context variable source 13 requireScript 7
Reserved characters, differences in escaping 30
Resources for developers 3
D Results processing 9
Data types
Base64 issues 13 S
converting 13
Debugging window 13 S-control sample 4
Samples 8
asynchronous calls 23
E how to use 14
Embedding calls in JavaScript 8 s-control 4
Error handling 28 synchronous calls 14
sessionId header option 26
set method 12
G SOAP headers 26
source context variable 13
get method 12 Support policy 3
Getting started 8 Synchronous calls
Getting started examples 8 error handling 28
introduction 11
H samples 14
52