[SalesForce] How to pass an array of strings to JavaScript array from Apex controller

How can I pass an array of strings EventDates from method public String[] eventDates() to the JavaScript array in my visualforce page? datesFromCalendar holds an array of dates coming from JavaScript and saved in salesforce in TextArea(Long). Now I want to send them back to JavaScript array. Any ideas?

public with sharing class EventsPageController {
    public Event__c Event{ 
     get {
      if (Event == null)
        Event = new Event__c();
      return Event;
    }
    set;
  }
    public String datesFromCalendar {get; set;}
    public List<String> eachDt = new List<String>();

    public void EventsPageController() {
        Event = [SELECT Id, EventDates__c,Event_Description__c,Event_Type__c,Maximum_Attendees__c,Occurrence__c,Program_Name__c FROM Event__c WHERE Id = :ApexPages.currentPage().getParameters().get('id')];

    }

    public Event__c getEvent(){
        return Event;
    }

    public String[] eventDates(){

      list<String> EventDates = new list<String>();
      list<Event__c> eventList = [SELECT Id, EventDates__c FROM Event__c WHERE Id = :ApexPages.currentPage().getParameters().get('id')];

      for(Event__c event : eventList) {
           EventDates.add(event.EventDates__c);
      }
      return EventDates;
}

    public PageReference saveData(){
        System.debug(datesFromCalendar);            
        try {
            Event.EventDates__c = datesFromCalendar;
            upsert(Event);
        } catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        // After Save, navigate to the default view page:
        return (new ApexPages.StandardController(Event)).view(); 

    }
}

Best Answer

There are 3 ways you can do that.

Method 1

First change the method to a getter method

public String[] geteventDates(){

      //your code
      return EventDates;
}

and then you can access in javascript something like this

<script>
 <apex:repeat value="{!eventDates}" var="event">
        console.log('the event is ==  {!event}');
    </apex:repeat>
</script>

Method 2

Serialize the List<String> using the JSON.serialize() and then use the JSON.parse() in the VF.

public String geteventDates(){

      //your code
      return JSON.serialize(EventDates);
}

in you VF:

var stringArray = JSON.parse('{!eventDates}');
for(var i=0;i<stringArray.length;i++) {
   console.log('The event is == '+ stringArray[i]);
}

Method 3

You can also use JS remoting. You can read about it here. But you cannot access instance variables in remoting methods. So you have to make the call which one you have to use.