0

I found the best answer here, but when I implemented it in my code, here's what happen to the dropdown select option:

"
1
"
:
"
t
e
s
t
1
"
,
(and so on).

What's wrong with it?

The ajax code in view:

$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/main/get_location",
data: data_loc,
success: function(locs)
{
    //alert(locs); when I do this, the alert shows: {"1": "test 1", "2": "test 2"}.
    $('#location').empty();
    $('#location').show();
    $.each(locs,function(id,location_description){
        $('#location').append($("<option></option>").attr("value",id).text(location_description));
    });
}

});

In controller:

public function get_location()
{
    $this->load->model("xms/model_db"); 
    echo json_encode($this->model_db->get_location_by_group($_POST['location_gr']));
}
Community
  • 1
  • 1
Marsha
  • 167
  • 3
  • 3
  • 18

1 Answers1

1

This is because locs is parsed as a string but not a json object. Try put datatype in your $.ajax like this:

$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/main/get_location",
data: data_loc,
dataType: 'json',
success: function(locs, dataType)
{
    $('#location').empty();
    $('#location').show();
    $.each(locs,function(id,location_description){
        $('#location').append($("<option></option>").attr("value",id).text(location_description));
    });
}

Or maybe using parseJSON:

$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/main/get_location",
data: data_loc,
success: function(result)
{
    loc = $.parseJSON(result);
    $('#location').empty();
    $('#location').show();
    $.each(locs,function(id,location_description){
        $('#location').append($("<option></option>").attr("value",id).text(location_description));
    });
}
kyo
  • 645
  • 4
  • 7