Populating a select box using JQUERY, AJAX and PHP

This answer provides the necessary modifications to your code.

DISCLAIMER: Without seeing the exact install, be aware there may be a variety of factors that cause this to not work “as-is” in your installation. I do not know how your routes are set up, or if you are using Firebug or some other console to watch the ajax calls, but this should give you the building blocks:

First, change your php to output the array as a json-encoded string:

public function getCars(){
        $this->load->model('car_model');

        $this->form_validation->set_rules('carId', 'carId', 'trim|xss_clean');

        if($this->form_validation->run()){
            $carId = $this->input->post('carId');
            $carModels = $this->user_management_model->getCarModels($carId);
            // Add below to output the json for your javascript to pick up.
            echo json_encode($carModels);
            // a die here helps ensure a clean ajax call
            die();
        } else {
            echo "error";
        }   
}

Then, modify your script ajax call to have a success callback that gets the data and adds it to your dropdown:

function myFunction(obj)
  {
    $('#emptyDropdown').empty()
    var dropDown = document.getElementById("carId");
    var carId = dropDown.options[dropDown.selectedIndex].value;
    $.ajax({
            type: "POST",
            url: "/project/main/getcars",
            data: { 'carId': carId  },
            success: function(data){
                // Parse the returned json data
                var opts = $.parseJSON(data);
                // Use jQuery's each to iterate over the opts value
                $.each(opts, function(i, d) {
                    // You will need to alter the below to get the right values from your json object.  Guessing that d.id / d.modelName are columns in your carModels data
                    $('#emptyDropdown').append('<option value="' + d.ModelID + '">' + d.ModelName + '</option>');
                });
            }
        });
  }

Again – these are the building blocks. Use your browser console or a tool such as Firebug to watch the AJAX request, and the returned data, so you can modify as appropriate. Good luck!

Leave a Comment