3

I want to generate some data for editing, filtered by the choice a user makes in a dropdown menu, but I don't want to complicate things.

I already have my project querying the database for a list of "trees", and populating a dropbox with the tree name, assigning the tree_id as its value.

All I want to do is, when the user makes a choice in the drop-down, have JQuery return a list of only that ID's relevant data (description, etc).

What's the simplest way to do that? Do I even need to make an AJAX request? Here's my code:

CONTROLLER:

$this->load->model('Model_form','', TRUE);
$data['trees'] = $this->Model_form->get_tree();
$this->load->view('view_form_tree', $data);

MODEL:

function get_tree(){
$query = $this->db->query('SELECT * FROM trees');
return $query->result();
}

VIEW:

<h1>Edit Tree</h1>
<select id="f_treeindex" name="f_treeindex" class="dd_black">
<option value=""></option>
<?php
foreach($trees as $tree){
    echo '<option value="' . $tree->id . '">' . $tree->tree_name . '</option>';
}
?>
</select>

<script type="text/javascript">
     $(document).ready(function() {
        $('#f_treeindex').change(function(){
            var tree_id = $('#f_treeindex').val();
            if (tree_id != ""){
                //DO WHATEVER I NEED TO DO TO CALL THE INFORMATION FOR THE TREE WHOSE ID MATCHES THAT SELECTED IN THE DROPDOWN
            }//end if
        }); //end change
     }); //end docready
</script>

Just a note that the SELECT * statement in the model will return the tree_id, tree_name, and tree_description.

1 Answer 1

4

If you make a 'show' controller method that returns a bare template with the data (ie: not with the full layout), you can do something like this:

$('#f_treeindex').change(function(){
    var tree_id = $('#f_treeindex').val();
    if (tree_id != ""){
        $.get('/controller_name/show', {id:tree_id}, function(data){
            $(this).parents('div').append(data);
        })
    }//end if
});

Wrap the <select> in a <div> so your jquery has something to append the resulting html to.

Also, I would rename get_tree() to get_trees(), that way you can also do a get_tree($id) that returns a single tree in your controller_name#show method, which you can have return a template without the layout, to be appended.

function show() {
    $this->load->model('Model_form','', TRUE);
    $data['tree'] = $this->Model_form->get_tree($this->params['id']);
    $this->load->view('single_tree_view', $data);
}

also, not 100% sure how your CI is set up, so your $.get line might need to be

$.get('/controller_name/show/'+tree_id, function(data){...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.