Populating a select box using JQUERY, AJAX and PHP

Populating a select box using JQUERY, AJAX and PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Populating a Cascading Select Box with jQuery, AJAX, and PHP

Building cascading select boxes—where the second dropdown updates based on the selection in the first—is a classic frontend requirement that often trips up developers new to asynchronous data handling. The core challenge lies not just in clearing the previous options, but correctly serializing the server-side array structure into valid HTML markup and injecting it back into the DOM without breaking your application state.

In the scenario provided, we have two <select> elements. The first, identified by id="Cars", triggers an event when changed. The second, id="emptyDropdown", needs to be emptied and repopulated with models relevant to the selected car brand. The backend logic is handled by a CodeIgniter controller method (getCars) that returns an array of arrays containing model names and IDs.

The first step in your jQuery success callback is ensuring the data structure matches what the browser expects. Your PHP function currently outputs a raw PHP array string if you rely on default echo behavior, but to be consumed by JavaScript, this data must be serialized into JSON. In CodeIgniter, you can achieve this by passing the data through the output driver or simply echoing json_encode() directly within the controller action.

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

    // Ensure validation runs and set error handling if needed
    if ($this->form_validation->run()) {
        $carId = $this->input->post('carId');
        $carModels = $this->user_management_model->getCarModels($carId);

        // Convert the array of models to a JSON string
        echo json_encode($carModels); 
    } else {
        // Return an error object or string in JSON format for easier parsing
        echo json_encode(['error' => 'Validation failed']);
    }   
}

On the client side, you must replace your current ???????? placeholder with logic that parses this JSON and iterates over the resulting objects. Since your PHP array uses associative keys like ModelName and ModelID, you can leverage jQuery's .each() method to loop through the data and append <option> elements dynamically.

Here is how you would complete the success function:

$.ajax({
    type: "POST",
    url: "/project/main/getcars",
    data: { 'carId': carId },
    success: function(msg){
        // Parse the JSON string returned by PHP into a JavaScript object
        var models = $.parseJSON(msg);

        if(models.error) {
            console.log(models.error);
            return;
        }

        $('#emptyDropdown').empty();

        $.each(models, function(index, model) {
            // Construct the option string
            // Ensure you handle the ModelName value correctly based on your actual DB column names
            var optionText = model['ModelName']; 
            var optionValue = model['ModelID'];

            $('#emptyDropdown').append(
                $('<option>', {
                    'value':  optionValue,
                    'text':   optionText
                })
            );
        });
    },
    error: function(xhr, status, error) {
        console.error('AJAX request failed:', error);
    }
});

There are a few critical considerations here regarding your specific implementation. First, the onchange event handler on the first dropdown calls myFunction(this). Inside that function, you are correctly retrieving the value of the selected option from the carId variable. However, ensure that the URL /project/main/getcars is accessible via POST and that your CodeIgniter routing configuration allows it.

A common pitfall in this architecture is forgetting to handle the case where no matching models exist. If $this->user_management_model->getCarModels($carId) returns an empty array, your JavaScript loop will simply do nothing after you call .empty(), which is generally acceptable behavior. However, if the database query fails due to a missing record but doesn't return an empty array (e.g., throws an exception or returns null), your JSON parsing might break. Always ensure your PHP controller explicitly returns a valid JSON structure even in error cases.

Furthermore, while using jQuery's .append() is efficient for small datasets, it can impact performance if you are dealing with thousands of items due to repeated DOM manipulation. In high-volume scenarios, building the HTML string in memory and appending it once is often faster, though for car models, the difference is negligible.

Finally, consider the user experience. When a user selects a brand like "Toyota," the second dropdown should immediately reflect available models. If the server response is asynchronous, you might want to disable the second dropdown while waiting for the AJAX call to complete ($('#emptyDropdown').prop('disabled', true)) and re-enable it once the options are populated. This prevents users from interacting with stale data or selecting items before the list has updated.

Our network