May 17, 2015

May 17, 2015
In this article, we are going to discuss about How to populate the dropdown values in Cakephp using AJAX. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP. CakePHP uses well-known software engineering concepts and software design patterns, such as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.

Step 1 :

Add the below code in your View File where you want to apply the Ajax Dropdown

<div id="zoneDiv"></div>

<script>
$(document).ready(function(){
    $('#HotelCountryId').change(function(){
        var countryID = $(this).val();
        $.ajax({
            dataType: "html",
            type: "POST",
            evalScripts: true,
            url: '<?php echo Router::url(array('controller'=>'zones','action'=>'ajaxzone'));?>',
            data: ({countryid:countryID}),
            success: function (data, textStatus){
                $("#zoneDiv").html(data);
          
            }
        });
    });
});
</script>

Step 2 :

Add the below code in your Controller function from where you want to populate data

public function ajaxzone($id = null) {
    // debug($this->request->data['countryid']);exit;
    $this->layout = 'ajax';
    $id = $this->request->data['countryid'];
    if (!$this->Zone->exists($id)) {
        throw new NotFoundException(__('Invalid zone'));
    }
    $options = array('conditions' => array('Zone.country_id' => $id));
    $this->set('zones', $this->Zone->find('list', $options));
}

Step 3:

The view file of this function ajaxzone.ctp

<?php   
  echo $this->Form->input('zone_id', array('class'=>'form-control','placeholder'=>'State'));
?>

0 comments:

Post a Comment