จากบทความก่อนหน้านี้ เราได้แนะนำถึงการใช้งาน Select2 และ ประยุกต์ การใช้งาน Select2 สร้างตัวเลือก จังหวัด อำเภอ และ ตำบล กันไปแล้ว
ซึ่ง เจ้าตัว Select 2 เป็น ปลักอิน สำหรับ จัดการ select box ให้มีความสามารถมากขึ้น เช่น searching , tagging , remote data sets , infinite scrolling เป็นต้น
ในบทความนี้ ทางเราจะขอแนะนำการใช้งาน Select2 ให้ สามารถ ค้นหา ข้อมูล จาก Database มาแสดงในช่อง ค้นหา โดยจะแสดงข้อมูล ตามที่ค้นหา ทำให้ สะดวกในการใช้งาน กรณีที่มีข้อมูลเป็นจำนวนมาก
ตัวอย่าง การ ค้นหารายชื่อ ประเทศ ต่าง ๆ จากช่อง Select box โดยค้นหาจาก ฐานข้อมูล Country
ตัวอย่างไฟล์ index.php
โดยการทำงาน นั้น Class ที่เรียกใช้ Function select2 (ตัวอย่าง กำหนดชื่อ class คือ js-data-example-ajax) จะทำการส่งค่า ตัวแปร ที่รับมาจากช่องกรอกข้อมูล แล้ว ใช้ Ajax ส่ง ค่าที่ได้ไปค้นหาที่ไฟล์ json_data.php โดยใน ไฟล์ json_data.php จะมีการ ใช้คำสั่ง SQL ค้นหาข้อมูล และ ส่งค่ากลับมาแสดงใน ช่อง ของ select box อีกครั้ง
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo Select2 With Ajax</title>
<!-- นำเข้า CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" >
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<!-- นำเข้า JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<div class="form-group">
<div class="col-md-12">
<select class="js-data-example-ajax form-control" >
<option selected="selected">select2/select2</option>
</select>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
/*กำหนดให้ class js-data-example-ajax เรียกใช้งาน Function Select 2*/
$(".js-data-example-ajax").select2({
ajax: {
url: "http://localhost/select2/json_data.php",/* Url ที่ต้องการส่งค่าไปประมวลผลการค้นข้อมูล*/
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // ค่าที่ส่งไป
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
});
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + repo.value + "</div></div></div>";
return markup;
}
function formatRepoSelection (repo) {
return repo.value || repo.text;
}
</script>
ตัวอย่างไฟล์ json_data.php
ในไฟล์ json_data.php จะมีการเชื่อมต่อ ฐานข้อมูล country และ รับค่าตัวแปร $_GET[‘q’] แล้ว นำค่าที่รับมาไปค้นหาโดยใช้ คำสั่ง SQL LIKE ในการ กรองข้อมูล ให้ได้ ข้อมูลที่มีคำที่ตรงกับ ค่าที่ส่งมา แล้ว ส่งกลับไป โดย ใช้ คำสั่ง json_encode เพื่อแปลงข้อมูลที่ได้ เป็นรูปแบบ Json โดย ไฟล์ index.php จะรับค่า Json กลับไปแสดงผล
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "country";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_set_charset($conn , "utf8");
$sql = "SELECT id, value FROM list WHERE value LIKE '".$_GET['q']."%' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$data[] = array(
"id"=> $row["id"],
"value" => $row["value"]
);
}
} else {
echo "0 results";
}
$json = array(
"total"=>"",
"items"=>$data
);
echo json_encode($json);
mysqli_close($conn);
?>