abhit
abhit

Reputation: 979

How to use Select2 ajax call to bring data from a function into a <select> field?

My function is

public function actionGetMy() {
        [
            {
                color: "red",
                value: "#f00"
            },
            {
                color: "green",
                value: "#0f0"
            },
            {
                color: "blue",
                value: "#00f"
            }
        ]
    }

Now how should I write select2 query to bring data into the field. The select field is

<select name="My[]" multiple id="my">  

Upvotes: 0

Views: 97

Answers (2)

Gopal Satpati
Gopal Satpati

Reputation: 136

You can use the ajax like that

<script>
$(document).ready(function(){
   $('#my').select2({
    minimumInputLength: 2,
    ajax: {
      url: "optionlist.php",
      dataType: 'json',
      data: function (term, page) {
        return {
          q: term
        };
      },
      results: function (data, page) {
        return { results: data };
      }
    }
  });
});
</script>

Upvotes: 1

D Coder
D Coder

Reputation: 572

i think you want like

<select name="My" id="my"> 
<?php
foreach($colors as  $value){
?>
   <option value="<?php echo $value['value']; ?>"> <?php echo $value['color']; ?> </option>
<?php
}
?>
</select>

Upvotes: 0

Related Questions