Using the AJAX Toolkit.html

Force.com Cookbook Sample Code
Chapter 3: Best Practices for Writing S-Controls - "Using the AJAX Toolkit in an S-Control"

This s-control queries Account data and displays it on the same tab where the s-control resides.

To download all the code samples, access the Cookbook. - Image:Key_icon.gif

<html>

  <head>
  <script src="/soap/ajax/10.0/connection.js"
          type="text/javascript"></script>
  <script>

    function setupPage() {

      //Function contains all code to execute after page is
      //rendered

      var state = { //The 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,

          //Call queryFailed if the API request fails

          onFailure: queryFailed,
          source: state};

      sforce.connection.query(
          "SELECT Id, Name, Industry FROM Account" +
          "ORDER BY Industry limit 30", callback);
  }

  function queryFailed(error, source) {
    source.output.innerHTML = "An error has occurred: "
                              + error;
  }

This method is 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 = "";

      //Get the records array

      var records = queryResult.getArray('records');

      //Loop through the records and construct HTML string

      for (var i = 0; i < records.length; i++) {
        var account = records[i];

        output += account.Id + " " + account.Name +

            " [Industry - " + account.Industry + "]<br>";
      }

    //Render the generated HTML string

    source.output.innerHTML = output;
    }
  }

  </script>

  </head>

  <body onload="setupPage()">
    <div id="output"> </div>
  </body>

</html>

Sample code provided by salesforce.com. All rights reserved.