0

I have 3 dropdowns with list of places that I wanted to sort in ascending order. The first dropdown of places is sorted using codeigniter active record order_by function and the places were successfully sorted in ascending order.However,using onchange javascript function,when I choose a place in the first dropdown then populate the second dropdown of places excluding the place I have chosen in the first dropdown, the places returned were not sorted in ascending order even though there is order_by function I have in my query. I suspect that this is because of the json formatted data returned in onchange. Here are my codes. Thanks for the help.

This code sorts the data properly in ascending order

function get_dropdown_barangay(){

  $query = $this->db->select('ID,brgy_name')
                    ->from('tbl_barangay')
                    ->order_by('brgy_name','asc')
                    ->get()
                    ->result_array();
  $dropdown = array('0'=>'Select Barangay');
  foreach($query as $value){
    $dropdown[$value['ID']] = $value['brgy_name'];
  }

  return $dropdown;

}

Output Image: enter image description here

Onchange code, the returned places are not sorted in ascending order

$('#brgy_id_1').change(function(){

    var brgy_id = $("#brgy_id_1").val();
    alert(brgy_id);
    var data_val = {'brgy_id':brgy_id};

    $.ajax({
         type: "POST",
         url:"<?php echo base_url();?>admin/get_barangay_list",
         data:data_val,
         dataType:'json',
         success: function(data)
          {
           $('#brgy_id_2').empty();
           $.each(data,function(id,val)
           {
                var opt = $('<option />'); // here we're creating a new select option for each group
                  opt.val(id);
                  opt.text(val);
                  $('#brgy_id_2').append(opt);
            });
           }
     });

 }); //end change

admin.php

function get_barangay_list(){

      if(isset($_POST['brgy_id2'])){
        $brgy_array_id = array('0'=>$_POST['brgy_id'],'1'=>$_POST['brgy_id2']);
      } else{
        $brgy_array_id = array('0'=>$_POST['brgy_id']);
      }

      $result=$this->core_model->get_barangay_list($brgy_array_id);
      $this->output->set_header('Content-Type: application/json',true);
      echo json_encode($result);
    }

model.php

function get_barangay_list($brgy_array_id){

  $query = $this->db->select('ID,brgy_name')
                    ->from('tbl_barangay')
                    ->where_not_in('ID',$brgy_array_id)
                    ->order_by('brgy_name','asc')
                    ->get()
                    ->result_array();
  $dropdown = array('0'=>'Select Barangay');
  foreach($query as $value){
    $dropdown[$value['ID']] = $value['brgy_name'];
  }

  return $dropdown;

}

Output Image showing data are not sorted in ascending order

enter image description here

4
  • Are you using Chrome? Chrome does not guarantee the order of items in objects. Commented Dec 5, 2013 at 10:31
  • Yes. I am using google chrome Commented Dec 5, 2013 at 10:32
  • If your returned data is an object (using strings as keys), then you can't guarantee the order. You can force it to sort properly by using numeric keys or an array. I am assuming of course that the DB functions are returning the data correctly. Commented Dec 5, 2013 at 10:33
  • How can I do that? How could I change my ajax code? When I alert the id and the val in my ajax in .each function, it seems that it is sortable because it returns the numeric id for the id parameter and string place for the val parameter Commented Dec 5, 2013 at 10:37

3 Answers 3

1

One way to implement kinghfb's comment :

On the server side : build an array

$dropdown = array();
$dropdown[] = array('id' => 0, 'label' => 'Select city');
for ($query as $value) {
    $dropdown[] = array('id' => $value['ID'], 'label' => $value['brgy_name']);
}

On the client side (javascript) : change your loop code :

$.each(data,function(id,val) {
    var opt = $('<option />'); // here we're creating a new select option for each group
    opt.val(val.id);
    opt.text(val.label);
    $('#brgy_id_2').append(opt);
});
Sign up to request clarification or add additional context in comments.

Comments

1

You are losing your order here, because you are setting new keys (problem is described here Change array key without changing order). So you have to keep the keys and due this you have to change the js part as well, because you can´t access the data using key-value anymore.

function get_dropdown_barangay(){

$query = $this->db->select('ID,brgy_name')
                ->from('tbl_barangay')
                ->order_by('brgy_name','asc')
                ->get()
                ->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
 $dropdown[] = array("id" => $value["ID"], "name" => $value['brgy_name']); // setting new value and keep an numeric key which represents the order
 }

  return $dropdown;

 }

and the js has to be like:

$('#brgy_id_1').change(function(){

    var brgy_id = $("#brgy_id_1").val();
    alert(brgy_id);
    var data_val = {'brgy_id':brgy_id};

    $.ajax({
         type: "POST",
         url:"<?php echo base_url();?>admin/get_barangay_list",
         data:data_val,
         dataType:'json',
         success: function(data)
          {
           $('#brgy_id_2').empty();
           $.each(data,function(object)
           {
                var opt = $('<option />'); // here we're creating a new select option for each group
                  opt.val(object.id);
                  opt.text(object.value);
                  $('#brgy_id_2').append(opt);
            });
           }
     });

 });

I had highlighted the changes, but I don´t know hot to use bold in code at SO....

Comments

0

You could sort your JSON using underscore

Just pass in your JSON and a sort function. Like so:

var cityJSON = [{city: 'San Vinente'}, {city: 'Pequnio'}, {city: 'Pili Drive'}, {city: 'Jc Aquino'}, {city: 'Banza'}];
console.log(cityJSON); // unsorted
cityJSON = _.sortBy(cityJSON, function(item){return item.city});
console.log(cityJSON); // sorted

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.