0

I'am struggling with select2.

I have an ajax call that returns me a json. The json is formated like that (from server):

 public function get_groups() 
    {
        $result = array();

        $sql = "SELECT * FROM auth_groups ";

        foreach ($this->db->query($sql)->result() as $row){
            $tmp = array("id" => $row->id ,"label" => $row->name );
            array_push($result, $tmp);
        }

        header('Content-type: application/json');
        echo json_encode($result);
    }

Then from my javascript i have :

$('#group_choice').select2({
            minimumInputLength: 2,
            ajax: {
                url: "/bonsejour/extranet/ajax/resources/get_groups",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term:term
                    };
                 },
                  results: function (data, page) {
                  var results = [];
                  $.each(data, function(index, item)
                  {
                    results.push({id:item.ID, text:item.label});
                  });

                  return {
                      results: results
                  };
                }
            }
        });

Where #group_choice is an input text.

When i type some text inside the input box it does shows all the elements coming from the json. But when i try to select an element nothing happens. How can i select the elements inside the input ?

Thanks

user1484668
  • 253
  • 2
  • 8

2 Answers2

0

Refer http://ivaynberg.github.io/select2/#documentation

formatSelection: formatSelectionMethod,

function formatSelectionMethod(row) { return row.text;}

I hope you will find it helpful.

Hemant Thorat
  • 2,386
  • 20
  • 14
0

Please refer to Select2 Ajax Method Not Selecting,

and take the correct value:

id: function(data){return {id: data.id};},

or

id: function(data){return data.id}
Community
  • 1
  • 1
Till
  • 1,097
  • 13
  • 13