Dynamically Add Item to jQuery Select2 Control using Ajax with PHP MySQL


Dynamically Add Item To JQuery Select2 Control Using Ajax With PHP MySQL

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:

In this tutorial we use web technology. Now we’ve moved on to how we can dynamically add options for the select2 control. So we need to extract the data from the countries table first, and then after loading that data into the HTML select tag. The selection fields are filled with dynamic MySQL data. 

Then we want to initialize the Select2 plugin, so we use $(‘#country’). Select2() this method. This method converts a simple selection field into a selection field at the front of the level with a search or filter function. To add a new option we need to add tag: true option with this method select2().  

 To add a new option, we use the select2: close event. So if we type something in the selection box and close that selection box, this event will appear. At this point we trigger an ajax query which sends an ajax query to the PHP script to add new options to MySQL, if the ajax request succeeds a new option is added to the select2 control.

 In PHP the script first checks whether the country already exists in the MySQL table or not. If the country does not exist in the table, a new country is added to the MySQL table and this option is loaded into the select2 selection box. So it’s a full process to dynamically add options to the jQuery Select2 plugin using Ajax with PHP scripts. Below is the complete source code for this tutorial.

Create Database and Table by SQL query

In first step, we need to create database and table, so here I created webscodex database and countries table with id, name column . You can simply create countries table as following SQL query.

Countries MySQL Table Structure

-- 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');

Created Database Configuration File

In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create config.php file on your root directory and put bellow code:

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);
	}
?>

Create Select2 HTML Form Page

In this step, we require to create index file in HTML for add and show country name in select option.this select option is searchable also add country name in database table dynamically using AJAX with PHP MySQL. we add all jquery CDN link and also select2 CDN link.

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>

Create PHP File for add Country Dynamically

In this step, we require to create add_country.php file for add country dynamically record using PHP MySQL.

add_country.php

<?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.😊


Leave a Reply