view: learning_view.php
Here is the first dropdown that I populate from the database.
<select name = 'category' id = 'category'> <option value="">-- Select Category --</option> <?php foreach($category as $item){ ?> <option value="<?php echo $item->id_cat; ?>"><?php echo $item->name; ?></option> <?php } ?> </select> <br><br>
I want to populate another drop-down menu, which depends on the first drop-down list. For this, I used the jQuery ajax post.
second drop-down menu:
<select name = 'type' id = 'type'> <option value="">-- Select Type --</option> <?php foreach($type as $item){ ?> <option value="<?php echo $item->id_type; ?>"><?php echo $item->name; ?></option> <?php } ?> </select> <br><br>
Ajax post:
jQuery(document).ready(function(){ $("#category").change(function() { var category_id = {"category_id" : $('#category').val()}; console.log(category_id); $.ajax({ type: "POST", data: category_id, url: "<?= base_url() ?>learning/dependent_dropdown", success: function(data){ $.each(data, function(i, data){ console.log(data.name); console.log(data.id_type) }); } }); }); });
controller: learn.php
public function dependent_dropdown() { if(isset($_POST['category_id'])) { $this->output ->set_content_type("application/json") ->set_output(json_encode($this->learning_model->getType($_POST['category_id']))); } }
The data comes from the database after the ajax message I checked
console.log(data.name); console.log(data.id_type)
in the console.
But it was not possible to figure out how to use the data in the second drop-down list of my view.
I mean, how can I populate the second drop-down menu with the data I got after the ajax post.
source share