[SalesForce] How to pass JavaScript array to Apex controller

Sorry for a simple question. I'm totally new to Salesforce.

I want to pass JavaScript array to Apex to save its data in the Salesforce custom object. I want to know the best approach to do it without JavaScript remoting. Following is the JavaScript code.

$("#saveCalendar").click(function () {
        getDatesBackup = document.getElementById('selectedDates').options;
        for(var k=0; k<getDatesBackup.length; k++){
            allSelectedDates.push(getDatesBackup[k].text);
            console.log("Dates Backup : "+getDatesBackup[k].text);
        }
        console.log(allSelectedDates);
    });

Best Answer

You can use ActionFunction for this. Here is sample for your reference.

Controller:

public class ActionFunctionCLS {

    public void IWantToDebug() {
        list<String> ls = ( List<String> )JSON.deserialize( Apexpages.currentPage().getParameters().get('node'), List<string>.class ) ;        
        System.debug('======================= ' + ls[0] );
        System.debug('======================= ' + ls[1]);
        System.debug('======================= ' + ls[2]);                
    }
}

VF Page:

    <apex:page controller="ActionFunctionCLS"  >

<script type="text/javascript">
    function doSave(node){
        var arr = ["foo", "bar", "baz"];
        paraFunction(JSON.stringify(arr));
    }       
</script>

<apex:form >
    <apex:actionFunction name="paraFunction" action="{!IWantToDebug}" rerender="view">      
         <apex:param id="anode" name="node" value="" />
   </apex:actionFunction> 
</apex:form>

 <input type="button" onclick="doSave();" value="test" />

Note that we are calling IWantToDebug Action from JS using paraFunction Action Function.

Related Topic