Home > Mobile >  Data not populating in select tag with AJAX request
Data not populating in select tag with AJAX request

Time:11-25

Currently I have a select tag that I want to fill in via a AJAX call every time the user clicks on that particular select tag. To do this I'm doing the following:

View class:

<label class="control-labels ">Property</label>
     <select name="property" class="form-control select2 selectsearch" <?php echo (isset($read) ? $read:''); ?> required>
     </select>

Ajax request:

$(document).ready(function(){  

    $("#property").click(function(){

    var post_url = 'listings/getonClick'
    $.ajax({
        type: "POST",
        url: post_url,
        data : { "hid" : $(this).val() },
        success: function(response){
            $.each(response, function(value, key) {
                $("#property").append("<option id=" value.id ">" value.name "</option>");
            })
        }
    });
});

Controller Class:

function getonClick(){

    $modelList = $this->listings_model->getProperties();

    echo(json_encode($modelList));
}

Model Class:

 function getProperties(){
    $this->db->select("id,name");
    $this->db->from("crm_project_properties");
    $query = $this->db->get();
    return $query->result_array() ;
 }

But after doing this, I cannot get any data in my select tag before or even after clicking on it

CodePudding user response:

Can ypu please try with .on("click")? Its worked for me in past

$(document).ready(function () {
     $("#property").on("click", '*:not(a)', function() {
       var post_url = 'listings/getonClick'
         $.ajax({
           type: "POST",
           url: post_url,
           data : { "hid" : $(this).val() },
           success: function(response){
                $.each(response, function(value, key) {
                   $("#property").append("<option id=" value.id ">" value.name "</option>");
           })
         }
      });
});

CodePudding user response:

You should encode your Response to JSON Object first

$(document).ready(function(){  

    $("#property").click(function(){

    var post_url = 'listings/getonClick'
    $.ajax({
        type: "POST",
        url: post_url,
        data : { "hid" : $(this).val() },
        success: function(response){
            var responseText = JSON.parse(response);
            $.each(responseText , function(value, key) {
                $("#property").append("<option id=" value.id ">" value.name "</option>");
            })
        }
    });
});

  • Related