Reputation: 199
I have been trying all the help available on different forums but now give up and posting my question here. Trying to populate dropdown using ajax call. Getting the data in json format successfully. But don't know to fill dropdown. code below: Controller:
function getRegion()
{
$this->load->model('Settings_model');
$title = $this->input->get('title');
$result = array("region" => $this->Settings_model->getSelectedRegion($title));
echo json_encode($result);
}
View:
$(document).on('change', '#campaignSel', function() {
changecampaign();
});
function changecampaign(){
var title= "New Normal";//$('#campaignSel option:selected').text();//$('#campaignSel').text();
$regionSel = $("#regionSel");
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getRegion'); ?>",
data:{ "title":"New Normal"},
datatype: "json",
success: function(result){
var appenddata;
$.each(result, function (key, value) {
appenddata += "<option value = '" + value.id + " '>" + value.region + " </option>";
});
$('#regionSel').html(appenddata);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Response: {"region":[{"id":"1","region":"109 FEATHERSTON ST (ELEC)\r\n"},{"id":"2","region":"ASHBURTON/MID CANTERBURY ELEC"}]} I want to fill dropdown with Regions.
Upvotes: 2
Views: 1583
Reputation: 199
Finally I resolved the issues in my code. I like to share the changes I made to my code below: added:
contentType: "application/json",
and
parsedobj = JSON.parse(result)
so the final ajax code is:
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getRegion'); ?>",
data:{ "title":title},
contentType: "application/json",
datatype: "json",
success: function(result){
parsedobj = JSON.parse(result)
var appenddata='';
$.each(parsedobj.region, function(index, value)
{
appenddata += "<option value = '" + index + "'>" + value.region + " </option>";
});
$('#regionSel').html(appenddata);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
Upvotes: 0
Reputation: 12085
you need to loop the region like this $.each(result.region, function (key, value) {
instead of result
Update1:
added if condition if ($.isArray(result.region)){ ... }
result = {"region":[{"id":"1","region":"109 FEATHERSTON ST (ELEC)\r\n"},{"id":"2","region":"ASHBURTON/MID CANTERBURY ELEC"}]}
var appenddata='';
if ($.isArray(result.region)){
$.each(result.region, function (key, value) {
appenddata += "<option value = '" + value.id + " '>" + value.region + " </option>";
console.log(appenddata);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1