Bad MVC - how to avoid it when using AJAX dropdown?

Hello friends,

At the risk of exposing my ignorance in CI / AJAX and getting pummeled for what I'm currently doing, can anyone help me with this issue?

I have a simple 2-tier dropdown:

- in the first dropdown you select your 'plant'.

- onChange, this dropdown runs controller /plant/Subtype/ via AJAX.

- /plant/Subtype/ has a method that calls /plant_model/Subtype_model

- /plant_model/Subtype_model runs a query that fetches all subtypes for that specific plant.

- now I know that the right thing to do would be to return $query; and send it back to the controller -- then send it to the view in order to populate a form_dropdown().

- but what I'm doing is echoing straight form the model to the browser:

// plant_model/subtype_model/
echo form_dropdown('plant_subtype', $options, $row->subtype);

Before you splatter you screen with projectile puke, understand that I'm doing this because the AJAX method I'm using clears up the DIV where the second dropdown should go.
function getPlantSubtype(strURL) {
            var req = getXMLHTTP();
            if (req) {
                req.onreadystatechange = function() {
                    if (req.readyState == 4) {
                        if (req.status == 200) {
                        } else {
                            alert("There was a problem while using XMLHTTP:\n" + req.statusText);
      "GET", strURL, true);

In that case, how would I run a loop through the items from the $query result if they were passed back to the controller, then to the view?

If anyone could give me the roadmap, it would be much appreciated!


[eluser]Agustín Villalba[/eluser]
I recommend you to pass the result from the model to the controller as an array, and after pass it to a view called "ajax_generic_dropdown_view" which receives the array and iterates over it generating the options of the dropdown.

Every layer should do their job


function subcategories () {
    $category_id = $this->uri->segment(3);

    // The Model
    $query = $this->categories->subcategories($category_id);
    $this->load->view('selectsubcategories', array('query' =>$query));


<?php foreach( $query->result() as $subcategory ) :?>
<option value="&lt;?php echo $subcategory->subcategory_id; ?&gt;">&lt;?php echo $subcategory->name;?&gt;</option>

Finally JS

url = 'http://localhost/../';
        category = $(this).attr('value')
        $('select[name=subcategory]').attr('disabled', 1);
            url + 'offer/subcategories/' + category,
            function complete(){
                $('select[name=subcategory]').attr('disabled', 0);

OK thanks to both - will try your suggestions

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.