TotalNewbie TotalNewbie - 6 months ago 74
Javascript Question

Populating a select box using JQUERY, AJAX and PHP

I posted a question earlier and didn't have much luck, I am hoping to clear the contents of a second dropdown and repopulate the dropdown, depending on the value that is in the first dropdown.

I have the following select boxes as seen below:

<select name = "car" id="Cars" onchange="myFunction(this)">
<option value="0">Toyota</option>
<option value="1">Audi</option>
<option value="2">Suzuki</option>
</select>


Underneath this dropdown I also have another drop down for models:

<select id="emptyDropdown">
<option value="0">R8</option>
<option value="1">Quattro</option>
<option value="2">A6 hatchback</option>
</select>


onchange I want to clear the second dropdown and populate it with models related to the car brand. EG.

Audi - A8, A6, A4 etc.
Suzuki - Swift, Panda etc.


<script>
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(msg){
?????????
}
});
}
</script>


I then have the following PHP function as seen below(I am using codeigniter) - this function uses the Car ID and returns a list of all the models as seen below:

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);
} else {
echo "error";
}
}


I then do not know how to return each element in the array produced in PHP, to repopulate the dropdown list with ID = "emptyDropdown".The array generated in PHP has the following structure:

Array ( [0] => Array ( [ModelName] => R8 V6 Twin Turbo [ModelID] => 19 ) [1] => Array ( [ModelName] => A6 Hatchback [ModelID] => 107 ) )


To clarify the question - how would I take each element in the array and put this as a new option in the dropdown list? is there a way to return the array to javscript and then repopulate in the success method of the ajax call?

Any help would be much appreciated, many thanks in advance

Answer

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!