Newer Version Available

This content describes an older version of this product. View Latest

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:

1var result = sforce.connection.query("select id, name from account");
2    var it = new sforce.QueryResultIterator(result);
3
4    while (it.hasNext()) {
5        var account = it.next();
6        sforce.debug.log(account.Name);
7    }
  1. The sforce.connection.query method returns a QueryResult object.
  2. A QueryResultIterator object is created and passed the QueryResult object.
  3. The code iterates through the records.

Differences in Escaping Reserved Characters

If you have a single quote or backslash in a string literal, you must use two backslashes instead of one to escape it. For example, the following statement in a Java client program is valid for finding account names like Bob's B-B-Q:

1SELECT ID from ACCOUNT WHERE Name LIKE 'Bob\'s B-B-Q%'

But if you are using the AJAX Toolkit, you need to escape the single quote literal character twice:

1SELECT ID from ACCOUNT WHERE Name LIKE 'Bob\\'s B-B-Q%'

Working with Base64 Binary Encoded Strings

Base64 encoding and decoding is very slow in JavaScript. Also, encoding and decoding does not work correctly for binary or multibyte strings. We do not recommend that you manipulate Base64 binary encoded strings with the AJAX Toolkit. However, if you want to read a document with Base64 binary encoding, you can use the API to query for the Id of the document and then download it directly from the server.

The following example demonstrates how to query for the document Id and then download it from the server:

1<html>
2<head>
3<script type="text/javascript" src="/js/dojo/0.3.1/dojo.js"></script>
4<script src="/soap/ajax/30.0/connection.js"></script>
5
6<script>
7function setup() {
8  var document_ta = document.getElementById("document-ta");
9
10  sforce.connection.query("select name, id from document limit 1",
11    {onSuccess : querySuccess,
12     onFailure : function(error, doc_ta) {
13        doc_ta.value = "Oops something went wrong: " + error;
14     },
15     source: document_ta});
16}
17
18function querySuccess(result, doc_ta) {
19  var records = result.getArray("records");
20
21  if (records.length == 1) {
22    dojo.io.bind({
23      url: "/servlet/servlet.FileDownload?file=" + records[0].Id,
24      load: loadDocument});
25  } else {
26    doc_ta.value = "no records found";
27  }
28}
29
30function loadDocument(type, data, event) {
31  var document_ta = document.getElementById("document-ta");
32  document_ta.value = data;
33}
34
35</script>
36</head>
37
38<body onload="setup()">
39<textarea id="document-ta" cols="80" rows="20">
40</textarea>
41</body>
42</html>

This example uses the JavaScript toolkit Dojo. For more information, see http://dojotoolkit.org/.

Note

Using the Timeout Parameter with Asynchronous Calls

If an asynchronous call does not complete in an appropriate amount of time, you can end the call. To do this, specify the timeout parameter in the callback section of any asynchronous call:
1var account = new sforce.SObject("Account");
2account.Name = "my new account";
3
4sforce.connection.create([account], {onSuccess: print, onFailure: printerr, timeout: 100});

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.

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.

Warning

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.

To use the AJAX proxy, you must register all external services in the Salesforce user interface, from Setup, in Security Controls | Remote Site Settings.

For security reasons, Salesforce 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.
  • 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections.

Note

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:

1sforce.connection.remoteFunction({
2                   url : "http://www.myExternalServer.com",
3                   onSuccess : function(response) {
4                          alert("result" + response);
5                      }
6               });

POST Example:

1var envelope = ""; //request envelope, empty for this example
2            sforce.connection.remoteFunction({
3                   url : "http://services.xmethods.net:80/soap",
4                   requestHeaders: {"Content-Type":"text/xml",
5                          "SOAPAction": "\"\""
6                      },
7                   requestData: envelope,
8                   method: "POST",
9                   onSuccess : function(response) {
10                          sforce.debug.log(response);
11                      },
12                   onFailure : function(response) {
13                          alert("Failed" + response)
14                      }
15               });

remoteFunction Syntax and Parameters

The remoteFunction syntax and parameters:

1sforce.connection.remoteFunction({ 
2url : endpoint_url, 
3onSuccess : callback_method 
4onFailure : error_callback 
5method : http_method 
6mimeType : "text/plain" | "text/xml" 
7async : true | false 
8requestHeaders : http_headers 
9requestData : http_post_data 
10cache : true | false 
11timeout : client_side_timeout_in_ms 
12});

cache and timeout are available in version 10.0 and later.

Note

Downloading the Salesforce Client Certificate

Your application (endpoint) server's SSL/TLS may be configured to require client certificates (two-way SSL/TLS), in order to validate the identity of the Salesforce server when it takes the role of client to your server. If this is the case, you can download the Salesforce client certificate from the Salesforce application user interface. This is the client certificate that Salesforce sends with each outbound message for authentication.

To download the certificate, use this procedure:
  • From Setup, click Develop | API to display the WSDL Download page.
  • In the WSDL Download page, right-click Download Client Certificate and save it to an appropriate location on your local drive.
  • Import the downloaded certificate into your application server, and configure your application server to request the client certificate. The application server then checks that the certificate used in the SSL/TLS handshake matches the one you downloaded.

Your application (endpoint) server must send any intermediate certificates in the certificate chain, and the certificate chain must be in the correct order. The correct order is:

  1. Server certificate.
  2. Intermediate certificate that signed the server certificate if the server certificate was not signed directly by a root certificate.
  3. Intermediate certificate that signed the certificate in step 2.
  4. Any remaining intermediate certificates. Do not include the root certificate authority certificate. The root certificate is not sent by your server. Salesforce 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.

Note