Query Data in Visualforce page without Controller using Connection.js

Using Connection.js we can query any salesforce record directly in Visualforce page without Apex Controller, so if you are creating a Visualforce page to display data or create a record you can do that directly in visualforce by just using the connection.js library.

Code to Retrieve data

Query Data in Visualforce page without Controller using Connection.js

<apex:page >
  <script type="text/javascript">
    var __sfdcSessionId = '{!GETSESSIONID()}';
  </script>

  <div id="output"> </div>

  <script src="../../soap/ajax/45.0/connection.js" type="text/javascript"></script>
  <script type="text/javascript">
    window.onload = setupPage;

    function setupPage() {
      var state = {
        output: document.getElementById("output"),
        startTime: new Date().getTime()
      };

      var callback = {
        onSuccess: layoutResults,
        onFailure: queryFailed,
        source: state
      };

      sforce.connection.query(
        "Select Id,Name From Account LIMIT 100",
        callback);
    }

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

    function layoutResults(queryResult, source) {
      if (queryResult.size > 0) {
        var output = '';
        output += '<tr>'
        output += '<th>Record ID</th>';
        output += '<th>Name</th>';
        output += '</tr>'

        //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 += '<tr>'
          output += '<td>' + account.Id + '</td>';
          output += '<td>' + account.Name + '</td>';
          output += '</tr>'
        }
        //render the generated html string
        source.output.innerHTML = '<Table>'+output+'</Table>';
      }
    }
  </script>
</apex:page>

Code to update a record

        var newRecords = [];
        var acc = new sforce.SObject("Account");
        acc.id ="{!Account.Id}";
        acc.Name = 'NewTestAccount';
        newRecords.push(acc);
        result = sforce.connection.update(newRecords);

Using AJAX Toolkit you can also perform DML operations

For more information go to this link https://developer.salesforce.com/docs/atlas.en-us.ajax.meta/ajax/sforce_api_ajax_introducing.htm?search_text=update

Was this post useful? If yes then please share.



Leave a Comment

All fields marked with an asterisk (*) are required


shares