How to get data in select2 with AJAX PHP


Step-1create a table with the below sql query.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2: Create index.html file.

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
</head>
<body>

</body>
<script>
$(document).ready(function(){
    $("#portLoading").select2({
        ajax: { 
            url: "get_data.php",
            type: "get",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    searchTerm: params.term /* search term */
                };
            },
            processResults: function (response) {
                return {
                    results: response
                };
            },
            cache: true
        }
    });
});
</script>

</body>
</html>

Step - 3 Create the config file.

config.php

<?php

$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "user_db"; 

$con = mysqli_connect($host, $user, $password,$dbname);
/* Check connection */
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

Step - 4 create the php file to get data.

get_data.php

<?php
include 'config.php';

if(!isset($_POST['searchTerm'])){ 
  $fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{ 
  $search = $_POST['searchTerm'];   
  $fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
} 

$data = array();
while ($row = mysqli_fetch_array($fetchData)) {    
  $data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
?>