My limits. I can not make this to work:
I want to make a dynamic select list with jquery and JSON to populate data from database
I see it fetches data in firebug console but it does not populate the select box.
Here’s my view:
<div class="control-group">
<label class="control-label" for="inputPassword">Grad</label>
<div class="controls">
<select name="city" id="city" class="update">
<option value="">Odaberi</option>
<?php if (!empty($results)) { ?>
<?php foreach($results as $row) { ?>
<option value="<?php echo $row->city_id; ?>">
<?php echo $row->city_name; ?>
</option>
<?php } ?>
<?php } ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deo grada</label>
<div class="controls">
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</div>
</div>
Here is my controller where i call my model:
function update_list(){
$this->marea->update_list();
And, finally my model
function update_list(){
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=isport', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `area`
WHERE `city_id` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Odaberi</option>');
foreach($list as $row) {
$out[] = '<option value="'.$row['area_id'].'">'.$row['area_name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
}
here my ajax:
var formObject = {
run : function(obj) {
if (obj.val() === '') {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
} else {
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON(SITE +'users/update_list', { id : id, value : v }, function(data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
return;
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
}
};
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
});
Your issue is the use of the jQuery
nextfunction,Your select box is not in the same set, so the next is returning an undefined and nothing is getting updated. If you just need to use this code once for this specific spot, you can add another class or id to your second selector to specify it.