N1CKN4M3
N1CKN4M3

Reputation: 55

Select2 filter not working

I use Select2 to handle my dropdownmenu. The dropdownmenu get's populated via "Ajax-call" to PHP, who get's data from Mysql.

The Select2 dropdownmenu offers serach function and filtering. When i type in something in the search field, the letters get underlined, but the filter doesn't work. So the list won't get filtered by the letters i type in. Why?

JS:

$(document).ready(function(){
$("#test").select2({
placeholder: "test",
minimumInputLength: 1,
ajax: {
    url: "test.php",
    dataType: 'json',
    //search term
    data: function (term, page) {
        return {
        q: term, // search term
        page: page
        };
    },
    results: function (data, page) {
    return { results: data};
    } //End of results
}, //End of Ajax
}); //End of select2

Upvotes: 3

Views: 3592

Answers (1)

N1CKN4M3
N1CKN4M3

Reputation: 55

The filtering must be done in server-side. This PHP script will make the filtering work.

PHP:

<?php
// setup databse connection
require_once('db.php'); 

// Select from database, i have set the limit to 40 to speed up results
$result = $db->prepare("SELECT * FROM table WHERE option LIKE :term ORDER BY option ASC LIMIT 0,40");

// bind the value for security with the wildcard % attached.
$result->bindvalue(':term','%'.$_GET["q"].'%',PDO::PARAM_STR);
$result->execute();

// make sure there are some results else a null query will be returned
if($result->rowcount() != 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)){
    $answer[] = array(
                    "id"=>$row['option_id'],
                    "text"=>$row['option']);
// the text I want to show is in the form of option
}
} else {
// 0 results send a message back to say so.
$answer[] = array("id"=>"0","text"=>"No Results Found..");
}

// finally encode the answer to json and send back the result.
echo json_encode($answer);

Upvotes: 1

Related Questions