Populating a select box using JQUERY, AJAX and PHP

72,126

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!

Share:
72,126
TotalNewbie
Author by

TotalNewbie

Updated on May 24, 2020

Comments

  • TotalNewbie
    TotalNewbie almost 4 years

    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

  • TotalNewbie
    TotalNewbie about 10 years
    thankyou I will give this a go - I'm still learning so I am not so good passing data between PHP and JS#
  • TotalNewbie
    TotalNewbie about 10 years
    all of your code seems to work apart from the last line - I have updated my question to include the array output - could you show me what this line should be: $('#emptyDropdown').append('<option value="' + d.id + '">' + d.modelName + '</option>'); if the array is as follows: ( [0] => Array ( [ModelName] => R8 V6 Twin Turbo [ModelID] => 19 ) [1] => Array ( [ModelName] => A6 Hatchback [ModelID] => 107 ) )
  • random_user_name
    random_user_name about 10 years
    @TotalNewbie - I've modified the code. Also, you may want to place inside the $.each function a console.log(d); to ensure you are getting what is expected. If it still doesn't work, add the console.log and post a comment here with the contents of the console log so we can see your data structure.
  • TotalNewbie
    TotalNewbie about 10 years
    Hi I actually got it working now thanks very much - A small typo on my part many thanks for all the help
  • Jayavinoth
    Jayavinoth about 5 years
    @cale_b - I am developing a settings page of my site. In the form, there are some values which will be auto populated from the DB on page load. I did this using only PHP and also by ajax & PHP. In PHP, the values are loaded on the page load but in ajax, values are getting reflected only after the page load so I can see the default value for 2-3ms. Please suggest which is better way to use?