I will share about Salesforce’s @RemoteAction.
Features
- You can execute Apex class processes from JavaScript.
- It has the same functionality as actionFunction, but you can use the return value of the process in JavaScript.
For example, you can execute a process to get accounts and use the list of accounts retrieved.
Sample code
- Apex class
global with sharing class SampleRemoteController {
@RemoteAction
global static String setString(String str) {
return '----- ' + str + ' -----';
}
@RemoteAction
global static List<sObject> exequery(String str){
return Database.query(str);
}
}
Visualforce pages
<apex:page controller="SampleRemoteController">
<apex:form >
<!-- @RemoteActionSample:StringSet -->
<apex:commandButton value=" String " onClick="return setString('Yaho');" />
<!-- @RemoteActionSample:SOQLGet -->
<apex:commandButton value=" GetAcc " onClick="return getAcc();" />
<hr/>
<div id="output">Output</div>
</apex:form>
<script type="text/javascript">
/*
* @RemoteActionSample
* StringSet
*/
function setString(str) {
{!$RemoteAction.SampleRemoteController.setString}(str, function(result, event){
if(event.status) {
document.getElementById("output").innerHTML = result;
}
});
return false;
}
/*
* @RemoteActionSample
* SOQLAccountGet
*/
function getAcc() {
var query = 'select Id,Name from Account limit 10';
{!$RemoteAction.SampleRemoteController.exequery}(query, function(result, event){
if(event.status) {
var names = '';
for (var i = 0; i < result.length; i++) {
names = names + result[i].Name + ' | ';
}
document.getElementById("output").innerHTML = names;
}
});
return false;
}
</script>
</apex:page>