Skip to Content, PHP, MySQL, Javascript, Ajax, Htacces

Synchronous and Asynchronous Calls with the AJAX Toolkit

Be First!
by March 1, 2012 Uncategorized

The AJAX Toolkit allows you to issue synchronous or asynchronous calls. Asynchronous calls allow the client side process to continue, waiting for a call back from the server. To issue an asynchronous call, you must include an additional parameter with the API call, referred to as a callback function. Once the result is ready, the server invokes the callback method with the result.

Synchronous syntax:

sforce.connection.method("arg1","arg2", ...);
For example:

Asynchronous syntax:

method("arg1","arg2", ..., callback_method);
For example:

var callback = {onSuccess: handleSuccess, onFailure: handleFailure};
function handleSuccess(result) {}
function handleFailure(error) {}
sforce.connection.query("Select name from Account", callback);

VF Page:

<script src="/soap/ajax/20.0/connection.js" type="text/javascript"></script>
window.onload = function() {
var AccountOutput = document.getElementById("AccountOutput");
var StartTime = new Date().getTime()
try {
 sforce.connection.sessionId = "{!$Api.Session_ID}"; //Used for Session out
 var queryResult = sforce.connection.query("Select Name, Industry From Account where Name!=null");
 AccountResults(queryResult, AccountOutput, StartTime);
} catch(error) {
 queryFailed(error, AccountOutput);
//if failed for Query
function queryFailed(error, out) {
 out.innerHTML = "<font color=red>An error has occurred:</font> <p>" + error;
//if gets Results and pass to 'out' variable
function AccountResults(queryResult, out, startTime) {
 var timeTaken = new Date().getTime() - startTime;
 if (queryResult.size > 0) {
  var AccountOutput = "";
  var records = queryResult.getArray('records');
  for (var i = 0; i <records.length; i++) {
  var account = records[i];
   AccountOutput += account.Name + "   [Industry -   "+   account.Industry + "  ]<BR>";
  out.innerHTML = AccountOutput + "<BR> query complexed in: " + timeTaken + " ms.";
 } else {
  out.innerHTML = "No records matched.";
<div id="AccountOutput">



Leave a Reply