In this tutorial, We will learn how to select2 with an ajax PHP example. I am going to show you an example for autocomplete jquery select2 with ajax PHP.



<html lang="en">
        <title>jquery select2 ajax php example</title>
        <link rel="stylesheet" href="" integrity="sha256-aAr2Zpq8MZ+YA/D6JtRD3xtrwpEz2IqOS+pWD/7XKIw=" crossorigin="anonymous" />
        <script src="" integrity="sha256-OFRAJNoaD8L3Br5lglV7VyLRf0itmoBzWUoM+Sji4/8=" crossorigin="anonymous"></script>
        <script src=""></script>
        <link href="" rel="stylesheet" />
        <script src=""></script>
        <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</h4>
                    <div class="card-body" style="height: 280px;">
                            <select class="postName form-control" style="width:500px" name="postName"></select>
        <script type="text/javascript">
                placeholder: 'Select an item',
                ajax: {
                    url: '/autocomplete.php',
                    dataType: 'json',
                    delay: 250,
                    data: function (data) {
                        return {
                            searchTerm: data.term // search term
                    processResults: function (response) {
                        return {
                            results: response
                    cache: true

To connect to database and select data from the db table.



define(DB_USER, "root");
define(DB_PASSWORD, "root");
define(DB_DATABASE, "new_blog");
define(DB_HOST, "localhost");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

if (!isset($_GET['searchTerm'])) {
    $json = [];
} else {
    $search = $_GET['searchTerm'];
    $sql = "SELECT, posts.title FROM posts 
                WHERE title LIKE '%" . $search . "%'
                LIMIT 10";
    $result = $mysqli->query($sql);
    $json = [];
    while ($row = $result->fetch_assoc()) {
        $json[] = ['id' => $row['id'], 'text' => $row['title']];

echo json_encode($json);

Thanks, May this example will help you...