+ 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 ;
   }
}