jQuery UI Autocomplete with PHP and Ajax

Apr 14, 2022 . Admin



Hello dev,

I am going to explain to you the jQuery UI autocomplete Ajax PHP example. You will learn jQuery UI autocomplete with PHP and AJAX.

This article will give you a simple example of how to jQuery PHP UI autocomplete dropdown. We will use get simple jQuery UI autocomplete Ajax PHP MySQL example.

I will give you a simple example of how to jQuery autocomplete Ajax PHP MySQL database.

So, let's see bellow solution:

config.php
<?php
    $host = "localhost";
    $user = "root";
    $password = "";
    $dbname = "my_db"; 

    $con = mysqli_connect($host, $user, $password,$dbname);

    if (!$con) {
        die("Connection failed: " . mysqli_connect_error());
    }
?>    
index.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Autocomplete with PHP and AJAX - Mywebtuts.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-11">
                <div class="card w-75 m-auto">
                    <div class="card-header text-center text-white bg-primary">
                        <h4>jQuery UI Autocomplete with PHP and AJAX - Mywebtuts.com</h4>
                    </div>
                    <div class="card-body">
                        <form>
                            <div class="mb-3">
                                <label class="mb-1"><strong>Single selection :</strong></label>
                                <input type='text' id='autocomplete' class="form-control">          
                            </div>
                            <div class="mb-3">
                                <label class="mb-1"><strong>Selected User id :</strong></label>
                                <input type='text' id='selectuser_id' class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="mb-1"><strong>Multiple Selection :</strong></label>
                                <input type='text' id='multi_autocomplete' class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="mb-1"><strong>Selected User ids :</strong></label>
                                <input type='text' id='selectuser_ids' class="form-control">
                            </div>
                        </form>             
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Script -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script type='text/javascript' >
        $(function() {
            $("#autocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                        url: "fetchData.php",
                        type: 'post',
                        dataType: "json",
                        data: {
                            search: request.term
                        },
                        success: function(data) {
                            response(data);
                        }
                    });
                },
                select: function (event, ui) {
                    $('#autocomplete').val(ui.item.label); // display the selected text
                    $('#selectuser_id').val(ui.item.value); // save selected id to input
                    return false;
                },
                focus: function(event, ui){
                    $("#autocomplete").val(ui.item.label);
                    $("#selectuser_id").val(ui.item.value);
                    return false;
                },
            });

            // Multiple select
            $("#multi_autocomplete").autocomplete({
                source: function(request, response) {
                    var searchText = extractLast(request.term);
                    $.ajax({
                        url: "fetchData.php",
                        type: 'post',
                        dataType: "json",
                        data: {
                            search: searchText
                        },
                        success: function(data) {
                            response(data);
                        }
                    });
                },
                select: function(event, ui) {
                    var terms = split($('#multi_autocomplete').val());
                    terms.pop();
                    terms.push(ui.item.label);
                    terms.push("");
                    $('#multi_autocomplete').val(terms.join(", " ));

                    // Id
                    var terms = split($('#selectuser_ids').val());
                    terms.pop();
                    terms.push(ui.item.value);
                    terms.push("");
                    $('#selectuser_ids').val(terms.join(", "));
                    return false;
                }
            });
        });

        function split(val) {
            return val.split(/,\s*/);
        }

        function extractLast(term) {
            return split(term).pop();
        }
    </script>
</body>
</html>
fetchData.php
<?php 
    include "config.php";

    if(isset($_POST['search'])){
        $search = mysqli_real_escape_string($con,$_POST['search']);

        $query = "SELECT * FROM users WHERE name like'%".$search."%'";
        $result = mysqli_query($con,$query);
        
        while($row = mysqli_fetch_array($result) ){
            $response[] = array("value"=>$row['id'],"label"=>$row['name']);
        }

        echo json_encode($response);
    }
    exit;
?>
Output:

It will help you...
#PHP