PHP JQuery Select2 Ajax Autocomplete Example

By Hardik Savani May 14, 2024 Category : PHP jQuery Ajax

Jquery select2 plugin is a very famous jquery plugin, using select2 plugin we can do several thing like select box with search, select option with check box, ajax auto-complete etc.

We normally require to do autocomplete task with select box when we have large amount of data like products, items, category, tag, user etc. so we can't load all then data at time and it's hard to find that item from several records. So select2 plugin provides us with select box with search and Ajax dynamically auto complete that way page will never load more and it will work fine.

In this example, I have two file one ajax.php that way it will give user layout and another for ajaxpro.php that will give items table records. i have also one "items" table and there are several records in that table when i will search from select box it will give me match result. This example you can run easily in your system too.

So, you can run this example using bellow code file and also you can check demo that will like as preview.



<html lang="en">


<title>Jquery select2 ajax autocomplete example code with demo</title>

<script src=""></script>

<link href="" rel="stylesheet" />

<script src=""></script>



<div style="width:520px;margin:0px auto;margin-top:30px;height:500px;">

<h2>Select Box with Search Option Jquery Select2.js</h2>

<select class="itemName form-control" style="width:500px" name="itemName"></select>


<script type="text/javascript">


placeholder: 'Select an item',

ajax: {

url: '/ajaxpro.php',

dataType: 'json',

delay: 250,

processResults: function (data) {

return {

results: data



cache: true








define (DB_USER, "root");

define (DB_PASSWORD, "root");

define (DB_DATABASE, "learn");

define (DB_HOST, "localhost");

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

$sql = "SELECT, items.title FROM items

WHERE title LIKE '%".$_GET['q']."%'

LIMIT 10";

$result = $mysqli->query($sql);

$json = [];

while($row = $result->fetch_assoc()){

$json[] = ['id'=>$row['id'], 'text'=>$row['title']];


echo json_encode($json);


Run PHP App:

All the required steps have been done, now you have to type the given below command and hit enter to run the PHP app:

php -S localhost:8000

Now, Go to your web browser, type the given URL and view the app output:


I hope it can help you...

Let's Check.....