<html lang="en">
<head>
<title>jquery select2 ajax php example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<div class="row mt-5">
<div class="col-md-6 offset-3 mt-5">
<div class="card">
<div class="card-header bg-info text-white">
<h4>JQuery Select2 Ajax PHP Example - Nicesnippets.com</h4>
</div>
<div class="card-body" style="height: 280px;">
<div>
<select class="postName form-control" style="width:500px" name="postName"></select>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('.postName').select2({
placeholder: 'Select an item',
ajax: {
url: 'autocompletePro.php',
dataType: 'json',
delay: 250,
data: function(data) {
return {
searchTerm: data.term
};
},
processResults: function(response) {
return {
results: response
};
},
cache: false
}
});
</script>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "root", "", "wordpress");
if (!isset($_GET['searchTerm'])) {
$json = [];
} else {
$search = $_GET['searchTerm'];
$sql = "SELECT wp_posts.ID, wp_posts.post_title FROM wp_posts WHERE post_status='publish' AND post_title LIKE '%" . $search . "%' LIMIT 10";
$result = $mysqli->query($sql);
$json = [];
while ($row = $result->fetch_assoc()) {
$json[] = ['id' => $row['ID'], 'text' => $row['post_title']];
}
}
echo json_encode($json);
?>