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.

Preview:

ajax.php

<html lang="en">

<head>

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

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.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 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>

</div>


<script type="text/javascript">

$('.itemName').select2({

placeholder: 'Select an item',

ajax: {

url: '/ajaxpro.php',

dataType: 'json',

delay: 250,

processResults: function (data) {

return {

results: data

};

},

cache: true

}

});

</script>


</body>

</html>

ajaxpro.php

<?php

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.id, 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:

http://localhost:8000/ajax.php

I hope it can help you...

Let's Check.....

Shares