PHP 8 Select2 Multi Select with jQuery AJAX Tutorial

Last updated on by Digamber

PHP Multi-select jQuery AJAX tutorial; in this tutorial, we will tell you how to profoundly create multiple select values functionality in PHP 8 using the jQuery Select2 plugin.

PHP Select2 MultiSelect AJAX

Moreover, we will create a playlist and store the multi-selected values into the database with the help of jQuery AJAX (Asynchronous JavaScript And XML).

Select2 is an excellent plugin empowered by JavaScript. You can create a highly customizable select box that comes with profound support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options. It is not just PHP, but it supports around 40 languages; you can combine it with AJAX to enable remote data support. You can add custom styling with CSS and SASS support, add items dynamically, and support a wide array of modern browsers.

PHP Multiple Select with Select2

In this tutorial, we will create a database connection file and an index file. In the database file, we will establish a database connection for storing select2 multiple select values. In the index file, we will add an input text field to store values and select box to choose multiple values, also add the select2 javascript file to create the multi-select autocomplete in PHP.

Create Table into Database

It seems to me you have already created the database; hence head over to the database and use the suggested SQL query to create a playlist table and add id, name, and songs values.

CREATE TABLE `playlist` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `songs` varchar(200) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Connection

Use the following code to create a database connection, define variables to post values, and SQL query to insert multi-select values into the database table.

You need to add the following code in database/db.php file:

<?php
    define (DB_USER, "root");
    define (DB_PASSWORD, "");
    define (DB_DATABASE, "test");
    define (DB_HOST, "localhost");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

    $name = $_POST['name'];
    $songs = implode(', ', $_POST['songs']);

    $sql = "INSERT INTO playlist (name, songs) VALUES ('$name', '$songs')";
    $result = $mysqli->query($sql);

    echo 'Data added in database'
?>

PHP Multi Select AJAX Example

Import Bootstrap 5 to style the PHP autocomplete component, then import the select2 CSS file inside the HTML file’s head section.

Add a form tag within the form tag, add an input text field, and a select box. Also, keep the Bootstrap alert box to show the response in conjunction with select2 autocomplete AJAX.

We define the static values into the select box; nonetheless, you can go ahead with the dynamic values.

<html lang="en">

<head>
    <title>PHP AJAX Multi Select Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</head>

<body>
    <div class="container mt-5" style="max-width: 550px">

        <div class="card-header alert alert-info text-center">
            <h2>PHP Multiple Select with Select2</h2>
        </div>

        <!-- Message -->
        <div class="res-msg mt-3 mb-3" style="display: none;">
            <div class="alert alert-success"></div>
        </div>

        <form method="POST">
            <div class="mb-3">
                <label class="form-label">Name</label>
                <input type="text" class="form-control" name="name">
            </div>

            <div class="mb-3">
                <label class="form-label">Songs</label>
                <select class="songs form-select" name="songs[]" multiple>
                    <option value="one">Anyone</option>
                    <option value="two">At My Worst</option>
                    <option value="three">Skin</option>
                    <option value="four">Hey Boy</option>
                    <option value="five">We Good</option>
                    <option value="six">Higher</option>
                    <option value="seven">2drunk</option>
                    <option value="eight">Lifestyle</option>
                    <option value="nine">Sacrifice</option>
                </select>
            </div>

            <div class="d-grid gap-2 mt-3">
                <button class="btn btn-danger add-data">Store</button>
            </div>
        </form>

    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.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 () {
            $('.songs').select2();
        });

        $('body').on('click', '.add-data', function (event) {
            event.preventDefault();
            var name = $('input[name=name]').val();
            var songs = $('.songs').val();
            $.ajax({
                method: 'POST',
                url: './database/db.php',
                data: {
                    name: name,
                    songs: songs,
                },
                success: function (data) {
                    console.log(data);
                    $('.res-msg').css('display', 'block');
                    $('.alert-success').text(data).show();
                    $('input[name=name]').val('');
                    $(".songs").val('').trigger('change');

                    setTimeout(function () {
                        $('.alert-success').hide();
                    }, 3500);


                }
            });
        });
    </script>
</body>

</html>

Conclusion

The select2 AJAX PHP example is done; for now, we had a chance to integrate the select2 plugin in the PHP application to create a search box with multiple selections that also work well as an autocomplete using AJAX and save the multi-select values into the database.