JavaScript <-> apex (Using @RemoteAction and Using apex:actionFunction)

<apex:page controller="remoting" >
 <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"/>
<div style="display:flex;"><input id="aNum" onblur="mulBy5();" value=""/> X 5 = <div class="result">0</div></div>
<div style="display:flex;"><input id="aNum1" onblur="mulBy15(j$(this).val());" value=""/> X 15 = <div class="result1"></div></div>
<script>
 j$ = jQuery.noConflict();
 function mulBy5(){
 Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.remoting.mulByFive}',
            j$("#aNum").val(), 
            function(result, event){
                if (event.status) {
                             j$(".result").html(result);
                } else if (event.type === 'exception') {
                        j$(".result").html(event.message + "<br/>\n<pre>" + event.where + "</pre>");
                } else {
                    j$(".result").html(event.message);
                }
            }, 
            {escape: true}
        );
      }
 </script>
 <apex:outputPanel id="rPanel">
 <script>
 j$(".result1").html({!controllerNum});
 </script>
 </apex:outputPanel>
 <apex:form >
  <apex:actionFunction action="{!mulNum}" name="mulBy15" rerender="rPanel">
        <apex:param name="firstParam" assignTo="{!controllerNum}" value="" />
    </apex:actionFunction>
 </apex:form>

 <style>
 .result{
 color:red;

 }
 </style>
</apex:page>


global class remoting {

    public PageReference mulNum() {
       controllerNum = controllerNum*15;
        return null;
    }


public Integer controllerNum {get;set;}
public remoting (){
controllerNum = 0;
}

@RemoteAction
global static Integer mulByFive(Integer n) { 
return n*5;
}
}

Choice of RemoteFucntion or ActionFunction would depend on the requirement, where the major difference between these two is RemoteFucntion cannot communicate with the rest of the controller and it also needs the controller to be a global class.

Comments

Popular Posts