iamjonesy
iamjonesy

Reputation: 25122

Filtering dropdown menu's with ajax and PHP

I have a CodeIgniter MVC application.

I have a model called city that has a method:

<?php
class Cities_model extends Model{    

function Cities_model(){
    parent::Model();
}

function get_cities($id = null){
    $this->db->select('id, city_name');

    if($id != NULL){
        $this->db->where('country_id', $id);
    }

    $query = $this->db->get('cities');

    $cities = array();

    if($query->result()){
        foreach ($query->result() as $city) {
            $cities[$city->id] = $city->city_name;
        }
        return $cities;
    }else{
        return FALSE;
    }  
}
...

Controller:

function Post(){
    $this->load->helper('form');
    $this->load->model('cities_model');
    $this->load->model('country_model');
    $this->load->model('field_model');

    $data['cities'] = $this->cities_model->get_cities();//optional $id parameter 
    $data['countries'] = $this->country_model->get_countries();

    $data['fields'] = $this->field_model->get_fields(); //subject field

    $this->load->view('post_view',$data);
}

This method is used to fill the contents of a dropdown list. I have a similar model for countries, which also has a dropdown.

You can see that the get_cities method is set up to accept a country_id. This would be used to filter the results if a country was selected.

My question is I need help calling this method using Ajax (preferably jQuery). I'm new to ajax and have never done anything like this before.

Any help most appreciated!

Billy

UPDATE

I've added jquery library and have created method in my controller:

function get_cities($country){
    header('Content-Type: application/x-json; charset=utf-8');
    echo(json_encode(array($this->cities_model->get_cities($country))));
}

here is my javascript on my view:

<script type="text/javascript">

  $(document).ready(function(){

  $('#country').change(function(){
    var country_id = $('#country').val();  // here we are taking country id of the selected one.
    $.ajax({
     type: "POST",
     url: "<?php echo base_url(); ?>home/get_cities/"+country_id,
     data: ({country : country_id}),
     success: function(cities){
       $.each(cities,function(i,city)
       {
          var opt = $('<option />');
          opt.val(city.value);
          opt.text(city.text);
          $('#cities').append(opt);
       });
    }

  });

  });
  });

This is the json reply:

[{"2":"Accra"}]

So it is successfully retriving the correct data. the only problem is it's adding blank values/text to the drop down. and each time I change the city the data is being added on, so I guess i'd have to clear the dropdown first?

Upvotes: 0

Views: 3753

Answers (2)

Dalen
Dalen

Reputation: 8996

extending Alpesh's answer:

you should have a controller's function which return cities filtered by country:

/controller/get_cities/<country>

i'm assuming that your controller's function will return a json object, you can obtain it by doing:

function get_cities($country)
{
   header('Content-Type: application/x-json; charset=utf-8');
   echo(json_encode(array($this->cities_model->get_cities($country))));
}

then on the view you'll have 2 select boxes:

  1. one filled up with the contries
  2. one empty and to be filled up with the cities retrived via ajax

now, you have to write something like Alpesh did in order to retrive the cities of the selected country; URL will be

url: '/controller/get_cities/'+country_id

while the success function would be something like

success: function(cities)
{
   $('#cities').empty();
   $.each(cities,function(i,city)
   {
      var opt = $('<option />');
      opt.val(city.value);
      opt.text(city.text);
      $('#cities').append(opt);
   });
}

UPDATE in your ajax success function you are dealing with a json objects, infact you are doing this:

opt.val(city.value);
opt.text(city.text);

where city is a json object and value and text are its properties.

when you generate the json via php you have to respect what you use in jquery so your model should return an array like this:

array
(
   array("value"=>"2","text"=>"Accra"),
   array("value"=>"3","text"=>"Kumasi"),
   ....
);

the json_encode that array and it should work. Maybe you don't need to wrap the model call into an array but i'm not sure depens on how you return the array

echo(json_encode(array($this->cities_model->get_cities($country))));

or

echo(json_encode($this->cities_model->get_cities($country)));

Upvotes: 1

Alpesh
Alpesh

Reputation: 5405

You can do it this way by jquery -

lets say you have 'country' as an id for the select for country -

then on change of country you can bring it's specific cities as follows -

$(document).ready(function(){

  $('#country').change(function(){
    var country_id = $('#country').val();  // here we are taking country id of the selected one.
    $.ajax({
     type: "POST",
     url: "the url you want to call",
     data: ({id : country_id}),
     success: function(cities){
     //populate the options of your cities dropdown here.
     }
  });

  });

});

you can refer detailed documentation here -

JQuery

Ajax API

Ajax

Upvotes: 1

Related Questions