Hello Everyone, In this tutorial, I am going to explain how to pass parameter in apex function or Apex method with help of javascript. In this example, I am showing account record list and provide a search functionality finds account according to the name that is input by the user in the search box. This search functionality uses apex:action function to pass the value in apex method using javascript.
After completing this tutorial, you’ll able to:
- Pass parameter in Apex function/method using javascript.
So let's start,
Passing parameter in the Apex method using Java-Script
Step 1: Open Developer Console, Go to File>New>Apex Class and create an Apex controller called AccountHandler. Replace the following code.
public class AccountHandler {
public List<Account> lstAcc{get;set;}
public AccountHandler(){
getAccoutList();
}
public void getAccoutList(){
String AccountName = ApexPages.currentPage().getParameters().get('AccountName');
String sQuery='SELECT Id, Name, Industry FROM Account';
if(AccountName !=null && AccountName!=''){
sQuery+=' WHERE Name LIKE \'%' + AccountName + '%\'';
}
System.debug(sQuery);
lstAcc=Database.query(sQuery);
}
}
Step 2: Open Developer Console, Go to File>New>Visualforce Page and create a new Visualforce Page called FindAccount and replace the following markup.
<apex:page controller="AccountHandler" showHeader="false" sidebar="false">
<apex:form id="thfrm">
<br/><br/>
<center>
<p style="font-size:20px;">
<u>Passing Parameter using Java Script</u>
</p>
Account Name :<input type='text' id='txtAccount' value=''/>
<input type="button" id="btnSearch" value='Search' onclick="getAccountList();"/><br/><br/>
</center>
<apex:actionFunction name="FindAccount" action="{!getAccoutList}" reRender="pbtbl">
<apex:param value="" name="AccountName"/>
</apex:actionFunction>
<apex:pageBlock id="pbtbl">
<apex:pageBlockTable value="{!lstAcc}" var="a">
<apex:column value="{!a.id}"/>
<apex:column value="{!a.Name}"/>
<apex:column value="{!a.Industry}"/>
</apex:pageBlockTable>
</apex:pageBlock>
<script>
function getAccountList(){
var searchString=document.getElementById('txtAccount').value;
if(searchString!=null && searchString!='' && searchString!=undefined){
FindAccount(searchString);
}
else{
FindAccount('');
}
}
</script>
</apex:form>
</apex:page>
Output:
See also:
- Get IP Address in Visualforce Page
- Find IP Address Geolocation in Visualforce
- Set PDF filename in Visualforce Page
Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.
4 Comments
Thanks that example really helped me out!
ReplyDeleteglad to know that it helpful for you.
DeleteThanks
please how could i send file to apex controller using java script ( do not use input file tag)
ReplyDeletetake the body of file as base64 encoding string and then pass it to apex controller
ReplyDeletePost a Comment