Thursday, December 6, 2012

Calling Force.com REST API from Javascript in Visualforce


Download the Forcetk.js from here and upload it in Static resources. Your Name > App Setup > Develop > Static Resources

 Include the forcetk.js and jquery.js in the Visualforce page in which you would like to call the REST API.


Here is the example code to display the Accounts list using REST API from java script in Visualforce page.


<apex:page standardController="Account">
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"/>
<apex:includeScript value="{!URLFOR($Resource.forcetk)}"/>
<script type="text/javascript">
// Get a reference to jQuery that we can work with
$j = jQuery.noConflict();
// Get an instance of the REST API client and set the session ID
var client = new forcetk.Client();
client.setSessionToken('{!$Api.Session_ID}');
var temp="";
client.query("SELECT Name FROM Account", function(response){
for (var i=0;i<response.records.length;i++)
{
    temp=temp+"<br/>"+response.records[i].Name;
}
$j('#accountname').html(temp);  
});
</script>
<p><u><b>Accounts:</b></u><br/><span id="accountname"></span>.</p>
</apex:page>


However it is good, but still this will increase the API calls.

Click here to see more information about the rest calls.

No comments:

Post a Comment