function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
cnp_nareshcnp_naresh 

How to invoke apex method from JavaScript

HI Every one,

 

    I have a visualforce page and corresponding apex class like this

<apex:page standardController="Event__c" extensions="CreateAnEvent">
...code.........
...code.........
</apex:page>

 Now I want to call a method in apex class, from JavaScript function.Can any one have any idea. Can you please help me in this requirement.

 

Thanks,

Naresh 

kiranmutturukiranmutturu

you can use action function

like 

 

<apex:page controller="actionfun">
  <apex:form >
      <apex:actionFunction action="{!call}" name="hold"/>
  </apex:form>
  <script>
  hold();
  </script> 
</apex:page>
 
bob_buzzardbob_buzzard

There's a couple of ways of doing this, javascript remoting will allow you to invoke an apex method and supply a javascript callback, while actionfunction will allow you to tie an apex method to a javascript function name and invoke that synchronously.

cnp_nareshcnp_naresh

HI Thanks for the reply.

 

    But my question is how to call the apex method, from  a javascript function.

 

Thanks,

Naresh

CaptainObviousCaptainObvious

You'll probably want to create a webservice. See the Apex in AJAX documentation for instructions.

Ankit AroraAnkit Arora

Here is the code :

 

VFP 

 

<apex:page controller="t">
<script>
    function myJavascriptFunc()
    {
        alert('Entered Javascript') ;
        CallApexMethod() ;
    }
</script>
<apex:form >
<apex:actionFunction name="CallApexMethod" action="{!myActionInController}" onComplete="alert('After apex method') ;"/>
  <apex:pageBlock >
        <apex:pageBlockButtons>
            <apex:commandButton value="Hit Me" onclick="myJavascriptFunc() ;"/>
        </apex:pageBlockButtons>
  </apex:pageBlock>
</apex:form>
</apex:page>

 

Class :

 

public class t
{
    public PageReference myActionInController()
    {
        return null ;
    }
}

 

As suggested by Bob you can also go with JavascriptRemoting, to know more visit this :

 

http://forceguru.blogspot.com/2011/06/summer-11-features-part-2-javascript.html

 

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

cnp_nareshcnp_naresh

Yes the above solution is perfectly working..Can anybody know, how to invoke a apex method from JavaScript with out page refresh?  Now I am able to call apex method from JavaScript, But page is refreshing every time.

 

              I want to call apex method from JavaScript with out page refresh.

 

Thanks,

Naresh B

Ankit AroraAnkit Arora

Just use this line :

 

<apex:commandButton value="Hit Me" onclick="myJavascriptFunc() ; return false ;"/>

 Or you can use reRender in action function.

 

Let me know if it works for you.

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

cnp_nareshcnp_naresh

Thanks for your reply. But the above statement is not working. Still my visualforce page is refreshing. 

 

Yes I can use Render in my visualforce. But my visualforce page contains <apex:inputfile.....> element.  

 

reRender  is not at all working if inputfile element is present in the visualforce page. 

 

The error that I am getting when I use <apex:inputfile.....> with rerender is

 

apex:inputFile can not be used in conjunction with an action component, apex:commandButton or apex:commandLink that specifies a rerender or oncomplete attribute

 

Thanks,

Naresh B

Ankit AroraAnkit Arora

reRender will not work with inputfile. I guess there is a workaround for this : create two different pageblock one is containing the button and other will have the inputfile. Then you can use reRender.

 

If you are not able to make this, I would suggest you to provide your code here and I will try to plunder some time to make it for you.

 

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

Swapnil GholapSwapnil Gholap
Hello Ankit, 
Your post, suggestion and code examples are up to the mark, it is very useful. Thanks for your work.

I am also Facing this issue : apex:inputFile can not be used in conjunction with an action component, apex:commandButton or apex:commandLink that specifies a rerender or oncomplete attribute
As you explained tried to create two different section , blocks for button and :inputFile, but no use.

I am uploading Countries with URL, then inside apex class I am making HTTP request , getting response, then adding Map of country etc..
Problem is, while uploading records(creating records) it takes time, so I want to give 'loding image' , it is not reRendering section or Block. Also at final , I want to display "Successful message"

<apex:page controller="CountryMap">
 
   <script>
    function myJavascriptFunc()
    {
        alert('Entered in Javascript') ;
        CallApexMethod() ;
    }
</script>

    <apex:form >
    <apex:actionFunction name="CallApexMethod" action="{!Upload}" reRender="Details" status="status"/>
  
    <apex:pageBlock title="Country Map Uploader" >
    <apex:pageBlockSection >
    <apex:inputFile value="{!CSVbody}" fileName="{!CSVstring}" />
    </apex:pageBlockSection>
    </apex:pageBlock>
      
      
      <apex:pageBlock>    
<!-- apex:commandButton value="Upload" action="{!Upload}" rerender="Details" onclick="createTabs();" status="status" / -->  
    <apex:commandButton value="Hit Me" onclick="myJavascriptFunc();"/>
   
    <apex:pageBlockSection id="Details" >
        <apex:actionStatus id="status" >
            <apex:facet name="start"  >
            <!--  <img src="/img/loading.gif" />    -->
            <img width="75px" height="75px" src="{!$Resource.processinggif}"/>               
            </apex:facet>
        </apex:actionStatus>


            
     </apex:pageBlockSection >
   <apex:pageMessages />
    </apex:pageBlock>
    
    </apex:form>
  
</apex:page>
DixitDixit
take your actionfunction off the form in the inputfile. 

And for images as "loading" or "succesfull", you can use action status.

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_actionStatus.htm 

 
Jessica RiffeJessica Riffe
We have several form pages that perform background saves without refreshing the pages.  We are using Action Functions with the reRender attribute.  If you want your page to call the apex method and not refresh or rerender anything, user reRender='';  However, it is usually a good idea to rerender your pageMessages in case there was an error during your behind the scenes save/method call.  

For the Input file problem.  We also ran into this issue and what I did was create a separate page that is only used for uploading attachments, then I put the page in my original forms with an iframe.
 
<apex:iframe id="uploadFrame" src="/apex/uploadattachment?id={!objectId}" height="60%" ></apex:iframe>

This solves the issue with not being able to upload an attachment when you do not want to reload the pages.
Sagar Nagvekar 14Sagar Nagvekar 14
For me onclick of <apex:commandButton> fails to call the controller method through the javascript function. But onkeyup of <apex:inputText> manages to call the controller method through the javascript function as seen in below code :-

<apex:page controller="June24Controller1">
  <script>    
    function myJavascriptFunc()
    {
        alert('Entered Javascript');
        afMethod1();
        alert('calling done to actionFunction');
    }
  </script>
  
  <apex:form >
    <apex:actionFunction name="afMethod1" action="{!method1}"/>
    
    <!-- This fails to call the controller method :- method1()    
    <apex:commandButton value="Click me" onclick="myJavascriptFunc();"/>
    
    <apex:inputText onkeyup="myJavascriptFunc();"/>
    
  </apex:form>
</apex:page>

The controller class :-
public class June24Controller1
{
    public Account a;
    
    public June24Controller1()
    {
        System.debug('////////////constructor runs');
        a = [select id, name from account where id = :ApexPages.currentPage().getParameters().get('id')];
        System.debug('////////////a is ' + a);
        
    }
    
    //public void method1() /* Return type of void instead of pageReference will also work with <apex:inputText> Visualforce element */
    public pageReference method1()
    {
        System.debug('////////////method1 runs from the controller');
        return null;
    }
}
Prashant Pandey07Prashant Pandey07
You may refer the following link..
https://developer.salesforce.com/forums/?id=906F000000099Z7IAI
Mahendra Singh 19Mahendra Singh 19
<apex:page controller="SmapleController">
            <script>
                    function CallJavascriptMethod()
                    {
                    CallmyApexMethods() ;
                    }
            </script>

            <apex:form >
        <apex:actionFunction name="CallmyApexMethods" action="{!myActionInController}"/>
            <apex:pageBlock >
                <apex:pageBlockButtons>
                    <apex:commandButton value="Click Me" onclick="CallJavascriptMethod() ;"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
            </apex:form>
        </apex:page>

//***********************Apex Class**************************//
public class SmapleController{

public PageReference myActionInController() {
return null ;
   }
}
Shilpa Goyal 9Shilpa Goyal 9
Hi All,
Can somebody help me, i tried ankit's code and alert messages are coming but action function is not calling on button click from JS
 
Shilpa Goyal 9Shilpa Goyal 9

Here is my Code
//VF CODE
<div>
                                                    <span style="float:left;font-size:16px;color:Orange;font-weight:bold;"><br/>&nbsp;Role1:&nbsp;&nbsp;
                                                    <apex:inputField value="{!Skill_Matrix__c.Role__c}" id="role1" onchange="callRole(this);"/></span>&nbsp; 
                                                    <span style="float:left;font-size:16px;color:Orange;font-weight:bold;"><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Role2:&nbsp;&nbsp;
                                                    <apex:inputField value="{!Skill_Matrix__c.Role__c}" id="role2"   onchange="callRole(this);"/>&nbsp;
                                                    <apex:actionfunction name="actfun1" action="{!getCompareRolesPage}"/>
                                                     <button class="button" type="submit" name="View Selected Roles" onclick="validate();" style="width:200px;height:20px;margin-left:56px">View Selected Roles
                                                     </button>
                                                    </span>
                                                </div>
//JS CODE
function validate()
    {
        var role1=document.getElementById('pg:mktoForm_2203:pb:role1').value;
        var role2=document.getElementById('pg:mktoForm_2203:pb:role2').value;
        if(role1 == '' || role2 == '')
            {
                alert('Please select appropriate Role values');
                //return;

            }else{
                actfun1();
            }
    }