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']));
}
2
  • locs is not valid json Commented Dec 3, 2014 at 3:30
  • 2
    if it was valid the alert would show [Object object] not the string Commented Dec 3, 2014 at 3:40

1 Answer 1

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));
    });
}
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.