JQuery Select2 Ajax PHP Example

11-Apr-2023

.

Admin

JQuery Select2 Ajax PHP Example

Hi Dev,

In this blog, I will learn you jquery select2 with ajax php example.I am going to show you example for autocomplete jquery select2 with ajax php.

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.

In this example, I have two file one autocomplete.php for user to show layout and another for autocompletepro.php that will give posts table records. i have also one "posts" 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.

Preview :


autocomplete.php

<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" integrity="sha256-aAr2Zpq8MZ+YA/D6JtRD3xtrwpEz2IqOS+pWD/7XKIw=" crossorigin="anonymous" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha256-OFRAJNoaD8L3Br5lglV7VyLRf0itmoBzWUoM+Sji4/8=" crossorigin="anonymous"></script>

<script src="//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 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 // search term

};

},

processResults: function (response) {

return {

results:response

};

},

cache: true

}

});

</script>

</body>

</html>

autocompletePro.php

<?php

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.id, 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);

?>

It will help you...

#PHP

#Jquery

#Bootstrap 4