title: SilverStripe - Pass data from controller to html form through jQuery.ajax
body: <p>I am working on a form which has 2 dropdowns: Service Requested and Locations. Whenever the user picks a service then the locations dropdown should be populated with those locations that have been selected for that service. I have an admin model for Service and Location, and here is the one for Service to show how I mapped the Locations model data to it:</p>
  
  <pre><code>&lt;?php
  class Service extends DataObject {
  
      private static $db = array(
          'Name' =&gt; 'varchar',
      );
  
      private static $belongs_many_many = array(
          'Locations' =&gt; 'Location'
      );
  
      public static $summary_fields = array(
          'Name' =&gt; 'Title',
      );
  
      private static $field_labels = array(
          'Name'
      );
  
      public function getCMSFields() {
  
          $fields = parent::getCMSFields();
  
          if ($this-&gt;ID) {
              $fields-&gt;addFieldToTab('Root.Locations', CheckboxSetField::create(
                  'Locations',
                  'Locations',
                  Location::get()-&gt;filter(array(
                      'AcceptingAppointments' =&gt; '1'
                  ))-&gt;map()
              ));
          }
  
          return $fields;
      }
  }
  </code></pre>
  
  <p>This is the jQuery related to the dropdown for Service Requested followed by the ajax function that is passing the id to the server:</p>
  
  <pre><code>  SchService.change(function() {
    if (SchService.val() != "" &amp;&amp; SchService.val() != null) {
      SchLocation.prop('disabled', false);
      sendServiceId();
    } else {
      SchLocation.prop('disabled', true);
    }
  });
  
    function sendServiceId(){
     var service_data = {
       serviceid: SchService.find('option:selected').attr('id')
     };
      $.ajax({
          type: "POST",
          url: "/home/getLocationsByService",
          data: service_data
      }).done(function (response) {
         console.log(response);
      });
  }
  </code></pre>
  
  <p>And finally, the function for getLocationsByService, which is using the Service id from the ajax call to retrieve the locations for that service:</p>
  
  <pre><code> public function getLocationsByService(){
      $serviceid = $this-&gt;getRequest()-&gt;getVar('serviceid');
      $service = Service::get()-&gt;byId($serviceid);
      $locations = Service::Locations();
      foreach ($locations as $location){
          return json_encode($locations);//not sure if this will be needed
      }
  }
  </code></pre>
  
  <p>I'm confused now on how to parse the location data retrieved in a manner that can be returned to the form for use in the Locations dropdown field. I am guessing json may be needed but that's as far as I've gotten. </p>