Salesforce | How to call apex method using Javascript

Author - Kiran Preet
26.07.2016
|
0 Comments
||

We can call apex method from javascript using JavaScript remoting.

Javascript remoting has three main parts :

1. Invoke remote method written in javascript method on Visualforce page.

2. Remote apex method contains an annotation @RemoteAction.

3. The response handler callback function written in javascript method on visualforce page.

Example of Javascript remoting :

<script type="text/javascript">
{
function saveval(val1)
 {
  var addTo ='kiran;sumit;shalini';
  if(addTo!='')
  {
   Visualforce.remoting.Manager.invokeAction(
   '{!$RemoteAction.TestClass.TestMethod}' ,     
   addTo ,"{!$CurrentPage.parameters.Id}",
   function(result, event)
    {                
    if(result)
     {
     window.opener.location.href="/{!$CurrentPage.parameters.Id}"; 
     window.top.close();
      }
   }, {escape:true}
  );
}
else
{
 alert('Please select the value from list.');
}
}
</script>

Here TestClass is a an apex class and TestMethod is a remote method.

Test Method :

@RemoteAction
public Static String TestMethod(string recordtype,Id RecordId)
{
Try
{
List Contacts=[Select id,name,emailId from Contacts where name in :recordtype ]  
return Contacts;
}catch(Exception e)
{
system.debug( e);
}
}

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Salesforce customization, App development or any other software development assistance please contact us at salesforce@webners.com

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *