Tuesday 10 November 2020

Dynamically Add Item to jQuery Select2 Control using Ajax with PHP



Do you know How to add option in Select2 jQuery plugin using Ajax with PHP language, If you not know then you have come on the right place because in this post you can find How to dynamically add option in Select2 jQuery plugin in PHP script using ajax. Here dynamically add option means that means you can add new option on page without going to another page and that option will be add in select2 jQuery plugin and that option will also store in Mysql database. So when you have filled form second time and at that time then you can also select last added option in select2 jquery plugin. This all process will be dynamically so when you have add new option then that data will be stored in database, so it is called dynamically added option in select2 jQuery plugin.

What is jQuery Select2 plugin?


jQuery Select2 plugin is a jquery plugin which has been used for convert simple select box to advance level select box, and after using Select2 plugin we can do searching feature in Select box, we can load remove data in select box, and it will also provide infinite scrolling of options result also. This Select2 plugin is also compatible with Bootstrap 3 and Bootstrap 4 library also. So we can easily use Select2 plugin with Bootstrap library also.


Which Web Technology used Under this Tutorial


Back-end Side


  1. PHP Script
  2. Mysql Database

Front-end Side


  1. jQuery
  2. Ajax
  3. Bootstrap 4
  4. Select2 jQuery Plugin





Mysql Database


First we have to create category table in our Mysql database. So for this run following SQL script in your mysql database. So it will make category table in your local database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `category`
--

CREATE TABLE `category` (
  `category_id` int(11) NOT NULL,
  `category_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `category`
--

INSERT INTO `category` (`category_id`, `category_name`) VALUES
(1, 'Automobile'),
(2, 'Chemicals'),
(5, 'Machinery'),
(6, 'Transport'),
(7, 'Computer'),
(8, 'Food'),
(9, 'Electronics');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `category`
--
ALTER TABLE `category`
  ADD PRIMARY KEY (`category_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `category`
--
ALTER TABLE `category`
  MODIFY `category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;





In this tutorial we have use above web technology, now we have proceed for how can we dynamically add option to select2 control. So first we have we have to fetch data from category table and then after we have load that data in HTML Select tag. So it it will fill select box with dynamic Mysql data.

Next we want to initialize Select2 plugin, so we have use $('.select2').select2() this method. This method will convert simple select box to advance level selectbox with searching or filtering feature. For add new option, we have to add tags:true option under this select2() method.

After this for add new option, we have use select2:close event. So when we have type something in select box and close that select box then this event occure and at that time we will trigger Ajax request, which will send Ajax request to PHP script for add new option into Mysql category table and on success of Ajax request it will append newly option to Select2 control.

At PHP script, First it will check category already exist in Mysql table or not. If category not exists in table then it will insert new category into Mysql table and that option will be load in select2 select box. So this is complete process of dynamically add option to Select2 jQuery plugin using Ajax with PHP script. Below you can find complete source code of this tutorial.

Source Code


database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

?>


index.php



<?php

//index.php

include('database_connection.php');

$query = "
  SELECT * FROM category 
ORDER BY category_name ASC
";

$result = $connect->query($query);

?>

<!DOCTYPE html>
<html>
  <head>
    <title>Dynamically Add New Option in Select2 using Ajax in PHP</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    	<!-- CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
    
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    
    <link href="https://raw.githack.com/ttskch/select2-bootstrap4-theme/master/dist/select2-bootstrap4.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
  </head>
  <body>
  	<div class="container">
  		<br />
  		<br />
    	<h1 align="center">Dynamically Add New Option Tag in Select2 using Ajax in PHP</h1>
    	<br />
    	<br />	
      <div class="row">
        <div class="col-md-6 offset-md-3">
          <select name="category" id="category" class="form-control form-control-lg select2">
            <?php
            foreach($result as $row)
            {
              echo '<option value="'.$row['category_name'].'">'.$row['category_name'].'</option>';
            }
            ?>
          </select>
        </div>
      </div> 
    </div>
  </body>
</html>

<script>

$(document).ready(function(){

  $('.select2').select2({
    placeholder:'Select Category',
    theme:'bootstrap4',
    tags:true,
  }).on('select2:close', function(){
    var element = $(this);
    var new_category = $.trim(element.val());

    if(new_category != '')
    {
      $.ajax({
        url:"add.php",
        method:"POST",
        data:{category_name:new_category},
        success:function(data)
        {
          if(data == 'yes')
          {
            element.append('<option value="'+new_category+'">'+new_category+'</option>').val(new_category);
          }
        }
      })
    }

  });

});

</script>


add.php



<?php

//add.php

include('database_connection.php');

if(isset($_POST["category_name"]))
{
	$category_name = preg_replace('/[^a-zA-Z0-9_ -]/s', '', $_POST["category_name"]);

	$data = array(
		':category_name'	=>	$category_name
	);

	$query = "
	SELECT * FROM category 
	WHERE category_name = :category_name
	";

	$statement = $connect->prepare($query);

	$statement->execute($data);

	if($statement->rowCount() == 0)
	{
		$query = "
		INSERT INTO category 
		(category_name) 
		VALUES (:category_name)
		";

		$statement = $connect->prepare($query);

		$statement->execute($data);

		echo 'yes';
	}
}

?>


Conclusion


In this post we have seen How to dynamically add option to select2 element using Ajax with jQuery and PHP. This feature mainly works if you fill some form and at the time of selection from select box and you want option which has not available in select box then by using this dynamically adding option feature will use for add new option into Select2 element without going to another page.

Lastly, If you have found that this tutorial is helpful to you then do not forget to share this post.

6 comments:

  1. This is so very useful. Thank you.

    ReplyDelete
  2. very useful thanks for sharing

    ReplyDelete
  3. your demo link of code is not working

    ReplyDelete
  4. I want to make a dropdown with search, add, and update features. Now, problem is that whenever select any value it automatically add to database. I want to make it that user search the option if it is not available then add it to database.

    ReplyDelete