Call a controller method from javascript in visualforce

Ramesh S picture Ramesh S · Jan 10, 2014 · Viewed 19.2k times · Source

How can I call a controller method from VisualForce page without any onclick event happening? My VisualForce page would be like

<apex:page standardController="Account"> 

    <script>
     /* Here i need to call a controller class with out any onclick event. It should load by itselef */

    </script>

</apex:page>

and my controller class will be like

public class OrderPadController {
    /* this will be the constructor */

    public PageReference openPage() {
         PageReference newpage = new Pagereference('/apex'+'/pagetoopen'+'?aid='+a.id); 
         openorderpadembed.setRedirect(false); 
         return openorderpadembed;      
    }

From my VisualForce page I need to call the method openPage().

Please help me out

Answer

Pavel Slepiankou picture Pavel Slepiankou · Jan 10, 2014

You can use JavaScript Remoting for Apex Controllers in the following manner:

<apex:page standardController="Account" extensions="OrderPadController">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      window.$j = jQuery.noConflict();
      $j( document ).ready(function() {
        OrderPadController.openPage(function(result, event){

            console.log(result);
            window.open(result,"_self");

        });
      });

    </script>
</apex:page>
public class OrderPadController {
    //

    @remoteAction
    public  PageReference openPage() {
        PageReference newpage = NEW Pagereference('/apex' + '/pagetoopen' + '?aid=' + a.id);
        openorderpadembed.setRedirect(false);
        return openorderpadembed;
    }
}