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">

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply

Your email address will not be published. Required fields are marked *