Saturday, December 10, 2016

Visualforce - Beyond Basics Series 10 - 5 ways to AJAX Calls

What is Ajax Call ?

After the initial page load, the client(browser) can interact with server asynchronously without page reload/redirection. This method is called AJAX technique. Its quite popular in modern web practices.

Why is it necessary ?

To build single page applications(SPA), we need to handle the interaction with server( POST calls) asynchronously & optionally update the portion of screen without full page reload. In order to achieve that AJAX calls are required.

What are the ways to achieve it ?

There are 5 ways one can use Ajax call in Visualforce,

  1. Remote Objects
  2. Action Functions
  3. Remote Methods
  4. SOAP API
  5. REST API


Where is code for each one ?

I have given example for each type, achieving the same result, i.e all the examples fetches 10 Opportunity records & display them in a div tag asynchronously.


Remote Objects

<apex:page >
<apex:sectionHeader title="Opportunities - Fetched through Remote Objects"/>
<!-- Remote Objects -->
<apex:remoteObjects>
<apex:remoteObjectModel name="Opportunity" fields="Id, Name, IsClosed"/>
</apex:remoteObjects>
<!-- Output -->
<apex:outputPanel layout="block" id="OutputArea"/>
<script>
window.onload = function() {
var oppModel = new SObjectModel.Opportunity();
console.log(oppModel);
oppModel.retrieve({limit : 10}, function(err, records, event) {
if (err) {
alert('Error while fetching records - ' + err);
} else {
records.forEach(function(rec) {
var div = document.getElementById('{!$Component.OutputArea}');
var newDiv = document.createElement('div');
var newContent = document.createTextNode(
' Id - ' + rec.get('Id') +
' Name - ' + rec.get('Name') +
' IsClosed - ' + rec.get('IsClosed'));
newDiv.appendChild(newContent);
div.appendChild(newDiv);
});
}
});
}
</script>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

Action Functions

<apex:page controller="testcls_1_08122016">
<apex:form>
<apex:sectionHeader title="Opportunities - Fetched through Action Methods"/>
<!-- Action Methods -->
<apex:actionFunction name="myCustAction_js" action="{!myCustAction}" rerender="OutputArea"/>
<!-- Output -->
<apex:outputPanel layout="block" id="OutputArea">
<apex:repeat value="{!lsOpp}" var="opp" rendered="{!lsOpp != Null}">
<apex:outputPanel layout="block">
Id - {!opp.Id}
Name - {!opp.Name}
IsClosed - {!opp.IsClosed}
</apex:outputPanel>
</apex:repeat>
</apex:outputPanel>
<script>
window.onload = function() {
myCustAction_js();
}
</script>
</apex:form>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

Remote Methods

<apex:page controller="testcls_1_08122016">
<apex:sectionHeader title="Opportunities - Fetched through Remote Methods "/>
<!-- Output -->
<apex:outputPanel layout="block" id="OutputArea"/>
<script>
/* Remote Methods */
testcls_1_08122016.getOpportunities(function(result, event) {
if (result) {
result.forEach(function(rec) {
var div = document.getElementById('{!$Component.OutputArea}');
var newDiv = document.createElement('div');
var newContent = document.createTextNode(
' Id - ' + rec['Id'] +
' Name - ' + rec['Name'] +
' IsClosed - ' + rec['IsClosed']);
newDiv.appendChild(newContent);
div.appendChild(newDiv);
});
} else {
alert('Error - ' + result);
}
});
</script>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

SOAP API

<apex:page >
<apex:sectionHeader title="Opportunities - Fetched through SOAP API"/>
<!-- Soap API - Include Scripts -->
<apex:includeScript value="{!URLFOR('/soap/ajax/9.0/connection.js')}"/>
<apex:includeScript value="{!URLFOR('/soap/ajax/9.0/apex.js')}"/>
<!-- Output -->
<apex:outputPanel layout="block" id="OutputArea"/>
<script>
window.onload = function() {
sforce.connection.sessionId = '{!$Api.Session_ID}';
sforce.apex.execute('testcls_1_08122016', 'getOpportunities_WS', {}, function(records){
if (records) {
records.forEach(function(rec) {
var div = document.getElementById('{!$Component.OutputArea}');
var newDiv = document.createElement('div');
var newContent = document.createTextNode(
' Id - ' + rec['Id'] +
' Name - ' + rec['Name'] +
' IsClosed - ' + rec['IsClosed']);
newDiv.appendChild(newContent);
div.appendChild(newDiv);
});
} else {
alert('Error - ' + records);
}
});
}
</script>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

REST API

<apex:page >
<apex:sectionHeader title="Opportunities - Fetched through REST API"/>
<!-- REST API -->
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"/>
<apex:includeScript value="{!URLFOR($Resource.ForceTK)}"/>
<!-- Output -->
<apex:outputPanel layout="block" id="OutputArea"/>
<script>
window.onload = function() {
var client = new forcetk.Client();
client.setSessionToken('{!$Api.Session_ID}');
client.query("SELECT Id, Name, IsClosed FROM Opportunity LIMIT 10",
function(result) {
if (result.records) {
result.records.forEach(function(rec) {
var div = document.getElementById('{!$Component.OutputArea}');
var newDiv = document.createElement('div');
var newContent = document.createTextNode(
' Id - ' + rec['Id'] +
' Name - ' + rec['Name'] +
' IsClosed - ' + rec['IsClosed']);
newDiv.appendChild(newContent);
div.appendChild(newDiv);
});
} else {
alert('Error - ' + result);
}
}
);
}
</script>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

A Class used for these examples,
global class testcls_1_08122016 {
public List<Opportunity> lsOpp { get; set;}
public void myCustAction() {
lsOpp = [Select
Id, Name, IsClosed
From
Opportunity
Limit 10];
}
@RemoteAction
public static List<Opportunity> getOpportunities() {
return [Select
Id, Name, IsClosed
From
Opportunity
Limit 10];
}
webservice static List<Opportunity> getOpportunities_WS() {
return [Select
Id, Name, IsClosed
From
Opportunity
Limit 10];
}
}
view raw gistfile1.txt hosted with ❤ by GitHub



No comments:

Post a Comment

Thanks for reading my blog !