Friday 21 March 2014

An Example showing How to Make Asynchronous calls with AJAX Toolkit

  1. <apex:page >  
  2.     <script type="text/javascript">  
  3.         var __sfdcSessionId = '{!GETSESSIONID()}';  
  4.     </script>  
  5.   
  6.     <script src="../../soap/ajax/29.0/connection.js" type="text/javascript" />  
  7.   
  8.     <script type="text/javascript"> window.onload = setupPage;  
  9.      
  10.   function setupPage() {  
  11.         //function contains all code to execute after page is rendered  
  12.         var state = { //state that you need when the callback is called  
  13.         output : document.getElementById("output"),  
  14.         startTime : new Date().getTime()};  
  15.     var callback = {  
  16.         //call layoutResult if the request is successful  
  17.         onSuccess: layoutResults,  
  18.         //call queryFailed if the api request fails  
  19.         onFailure: queryFailed,  
  20.         source: state};  
  21.          
  22.     sforce.connection.query("Select Id, Name, Industry From Account order by Industry limit 30", callback);  
  23.     }  
  24.   
  25.     function queryFailed(error, source) {  
  26.         source.output.innerHTML = "An error has occurred: " + error;  
  27.     }  
  28.   
  29.     /** 
  30.     * This method will be called when the toolkit receives a successful 
  31.     * response from the server. 
  32.     * @queryResult - result that server returned 
  33.     * @source - state passed into the query method call. 
  34.     */  
  35.   
  36.     function layoutResults(queryResult, source) {  
  37.   var timeTaken = new Date().getTime() - source.startTime;  
  38.   if (queryResult.size > 0) {  
  39.   var output = "";  
  40.   //get the records array  
  41.   var records = queryResult.getArray('records');  
  42.   //loop through the records and construct html string  
  43.   for (var i = 0; i < records.length; i++) {  
  44.   var account = records[i];  
  45.   output += account.Id + " " + account.Name +" [Industry - " + account.Industry + "]<br>";  
  46.   }  
  47.   //render the generated html string  
  48.   source.output.innerHTML = output  + "<BR> query completed in: " + timeTaken + " ms.";  
  49.   }  
  50.     }  
  51.     </script>  
  52. <div id="output"> </div>  
  53. </apex:page>  


Quick Link to parent document:  Embedding API Calls in JavaScript

No comments:

Post a Comment

Thank you for visiting. Your comments are highly appreciated.