How to load data using PHP Ajax in Select2

To load data using PHP and Ajax with the Select2 library, you can follow these steps:

Step 1: Setup Your HTML File

Start by creating an HTML file that includes the Select2 library and a <select> element to which you want to apply Select2. Make sure to include jQuery as Select2 depends on it. You can download Select2 and jQuery or include them from a CDN.

<!DOCTYPE html>
    <title>Select2 with PHP and Ajax</title>
    <link rel="stylesheet" href="">
    <script src=""></script>
    <script src=""></script>
    <select id="mySelect" style="width: 300px;"></select>
        $(document).ready(function() {
            // Initialize Select2

Step 2: Create the PHP Script

Next, create a PHP script that will fetch the data you want to populate in your <select> element. For this example, I'll assume you want to retrieve data from a database. You can adjust this part according to your data source.

// Include your database connection logic here
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

// Fetch data from the database
$sql = "SELECT id, name FROM your_table_name";
$result = $conn->query($sql);

// Create an array to store the data
$data = array();

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = array(
            'id' => $row['id'],
            'text' => $row['name']

// Output the data as JSON
echo json_encode($data);

// Close the database connection

Step 3: Load Data with Ajax

Modify your JavaScript code to use Ajax to fetch data from the PHP script and populate it into the Select2 dropdown.

$(document).ready(function() {
    // Initialize Select2
        ajax: {
            url: 'your_php_script.php', // Replace with the actual path to your PHP script
            dataType: 'json',
            delay: 250,
            processResults: function(data) {
                return {
                    results: data
            cache: true
        minimumInputLength: 0 // Set this to control when the dropdown appears (0 means it appears as soon as the user clicks)

Replace your_php_script.php with the actual path to your PHP script that fetches and returns data in JSON format. The PHP script should return an array of objects with id and text properties for Select2 to work correctly.

With these steps, you'll have a Select2 dropdown that loads data from a PHP script using Ajax. When a user types in the dropdown, it will send an Ajax request to your PHP script, which should respond with the matching data.

Muhammad Alfaiz
Alfaiz 6 months ago
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x