[SalesForce] Correct syntax to pass the parameter to a method via JavaScript (JavaScript remoting doesn’t have PageReference context)

I have a @RemoteAction method which return a List of opportunities via a SOQL statement that needs to use the dynamic 'WHERE Account.Id =: ApexPages.currentPage().getParameters().get('id')'.

This wasn't working though because it transpires, as per the docs, that JavaScript remoting is async and therefore, there is no PageReference context.

The solution apparently, as per ApexPages.currentPage().getParameters with javascript remoting, is to pass the parameter(s) explictly to a a method from JavaScript.

My code is below and although I am not getting any errors when I save the respective VF page (it's actually a VF component, but I don't think that matters) or the method, the data is not being displayed as expected on the Visualforce page.

Can someone please advise?

Thanks,

  @RemoteAction //Remote Action to expose method to JavaScript Remoting
public static List<Opportunity> getDatatable(Id accountid){
   return [select name, stagename, createddate, amount from Opportunity WHERE Account.Id=: accountid ORDER by Name ASC ];
           } 

 "fnInitComplete": function(oSettings) { 
                  ChartController.getDatatable('{!$currentPage.parameters.id}')(function(result, event){

FYI to readers: another good sources to read: Do RemoteAction methods have access to page parameters?

Best Answer

Remote action can be called with following syntax.

<script type="text/javascript">
    "fnInitComplete": function(oSettings) { 

        var recordid='{!$currentPage.parameters.id}';
        alert(recordid);
        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.ChartController.getDatatable}',
            recordid, 
            function(result, event){
                if (event.status) {

                    //your success code

                } else if (event.type === 'exception') {
                    //Your exception handling
                } else {

                }
            }, 
            {escape: true}
        );
    }
    </script>
Related Topic