Do you know how to add options to jQuery Select2 plugin using Ajax using PHP? If you don't know, you've come to the right place, because this post is for information on how to dynamically add options to the jQuery Select2 plugin in a PHP script using Ajax. Adding options dynamically allows you to add new options to a page without moving to another page. This option will be added to the jQuery select2 plugin and this option will also be saved in the MySQL database when you fill in the options. If you are working for the second time, you can also select the last option at this point in jquery. the select2 plugin has been added. The whole process is dynamic. So when you add a new option the data is stored in the database so it is called dynamically added options in the jQuery select2 plugin.
What is jQuery Select2 plugin?
The jQuery Select2 plugin is a jQuery plugin that is used to modify a simple selection box to iterate through a layer selection box. After we use the Select2 plugin, we can perform a search function in the selection box and load the data to delete into the selection box and it will also lead to endless scrolling options. This Select2 plugin is also compatible with Bootstrap 3 and Bootstrap 4 libraries. So we can easily use the Select2 plugin with the bootstrap library.
Preview:
Follow This Steps below
- Create Database and Table by SQL query
- Create Database Configuration File
- Create Select2 HTML Form Page
- Create PHP File for Add Country Dynamically
Step 1. Create Database and Table by SQL query
-- Database: `webscodex`
-- --------------------------------------------------------
-- Table structure for table `countries`
--
CREATE TABLE `countries` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(80) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `countries`
--
INSERT INTO `countries` (`id`, `name`) VALUES
(1, 'INDIA'),
(2, 'AMERICA'),
(3, 'CHINA'),
(4, 'LONDAN'),
(6, 'JAPAN'),
(7, 'PAKISTAN');
Step 2. Created Database Configuration File
config.php
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'webscodex');
/* Attempt to connect to MySQL database */
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . $conn->connect_error);
}
?>
Step 3. Create Select2 HTML Form Page
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dynamically Add Item to jQuery using Select2 js Ajax with PHP Mysql</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" />
<link rel="stylesheet" href="https://raw.githack.com/ttskch/select2-bootstrap4-theme/master/dist/select2-bootstrap4.css"/>
</head>
<body>
<div class="card bg-dark text-white text-center" style="padding:20px;">
<h3>Dynamically Add Item to jQuery using Select2 js Ajax with PHP Mysql</h3>
</div><br>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3">
<div class="card">
<div class="card-body">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<div class="form-group">
<select class="form-control select2" id="country" name="country-name" >
<?php
//Include database connection file
include_once('config.php');
$query = "SELECT * FROM countries ORDER BY name ASC";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
}
?>
</select>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').select2({
placeholder:'Select Country name',
theme:'bootstrap4',
tags:true,
}).on('select2:close', function(){
var element = $(this);
var new_country = $.trim(element.val());
if(new_country != '')
{
$.ajax({
url:"add_country.php",
method:"POST",
data:{new_country:new_country},
success:function(result)
{
data = JSON.parse(result);
if(data.error == '1')
{
alert(data.message);
element.append('<option value="'+new_country+'">'+new_country+'</option>').val(new_country);
}
}
});
}
});
});
</script>
</body>
</html>
Step 4. Create PHP File for add Country Dynamically
<?php
//Include database connection file
include_once('config.php');
if(isset($_POST["new_country"]) && !empty($_POST["new_country"]))
{
$country_name = preg_replace('/[^a-zA-Z0-9_ -]/s', '', $_POST["new_country"]);
$query = "SELECT * FROM countries WHERE name = '$country_name'";
$result = $conn->query($query);
if ($result->num_rows == 0) {
$query = "INSERT INTO countries (name) VALUES ('$country_name')";
if($conn->query($query)){
echo json_encode(array('error' =>'1', 'message' =>'Country added Successful'));
}
}
}
?>
Conclusion
In this post, we have seen how to dynamically add options to select2 elements using Ajax using jQuery and PHP. This function mainly works if you are also filling out a form while selecting from a selection field and want an option that is not available in the selection field. When you use this feature to add options dynamically, new options are added in the Select2 element without opening another page.
You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions / problems about this tutorial, please comment on the form below.😊
Post a Comment