Using actionFunction to Call Apex Methods from JavaScript

Using  <apex:actionFunction> Component

This standard Visualforce component provides a simple way to invoke an Apex controller action method directly from JavaScript code. The benefit here is that you can invoke serverside logic written in your Apex controller or controller extension directly from JavaScript code on the Visualforce page. In addition to providing an easy way to call Apex methods, supports AJAX and the ability to specify a rerender target. This allows you to refresh a portion of your Visualforce page based on the response from the server.

The element takes the following form:

<apex:actionFunction action=”{!methodInApexController}”  name=”javascriptMethodName” rerender=”none”>
….

javascriptMethodName();

The one drawback is that the Apex controller or controller extension cannot return data back to the invoking JavaScript code. Another consideration is the AJAX request will include the page’s view state, which can affect performance.

Controler –

public class muActionFunController {
public PageReference controllerMethod() {
return null ;
}
}

VF Page –

function myJavascriptFunc()
{
alert(‘Entered Javascript’) ;
CallApexMethod() ;
}

<apex:form >
<apex:actionFunction name=”CallApexMethod” action=”{!controllerMethod}” rerender=”none”/>
<apex:pageBlock >
<apex:pageBlockButtons>
<apex:commandButton value=”Hit Me” onclick=”myJavascriptFunc() ;”/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s