How To Add Loader Spinner Input Select2 JS In Laravel With Ajax

Risqi Ahmad
5 min readFeb 7, 2024

--

create loading spinner in select2 js

Are you looking to enhance the user experience on your Laravel application by adding loader spinners to Input Select2 elements using JavaScript? Look no further! In this comprehensive guide, we’ll walk through the steps to integrate loader spinners seamlessly with Input Select2 elements in your Laravel project using AJAX. By following these instructions, you’ll be able to provide a smoother and more visually appealing user interface for your application.

Getting Started with Laravel and Select2

Before we dive into the specifics of adding loader spinners, let’s ensure we have a basic understanding of Laravel and Select2.

What is Laravel?

Laravel is a powerful PHP framework known for its elegant syntax and developer-friendly features. It facilitates the development of web applications by providing a robust set of tools and conventions.

What is Select2?

Select2 is a jQuery-based replacement for HTML select boxes. It offers advanced features such as searching, tagging, infinite scrolling, and remote data loading, making it an ideal choice for enhancing select elements in web applications.

Preparing Data

We will use models and migrations to store the data that will be utilized.

First, create migration and model

php artisan make:migration create_employeers_table

This is code migration table.

Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});

And then, running migration.

 php artisan migrate

Create model Employee.php.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
use HasFactory;

protected $fillable = [
'name',
];
}

Using Seeder And Faker

We will use seeder and faker to create dummy data. In Laravel, a seeder is a class used to populate the database with test data. It is particularly useful for development and testing purposes, allowing developers to quickly fill the database with sample data for testing functionalities or demonstrating features.

Faker, on the other hand, is a PHP library integrated into Laravel that generates fake data for various data types, such as names, addresses, emails, and more. It’s commonly used in conjunction with seeders to create realistic but randomized data for testing and development purposes. Faker makes it easier to generate large amounts of dummy data quickly, saving time and effort during the development process.

Let’s started

php artisan make:seeder EmployeeSeeder

Create faker in database/seeders/EmployeeSeeder.php

<?php

namespace Database\Seeders;

use App\Models\Employee;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class EmployeeSeeder extends Seeder
{
public function run()
{
$faker = Faker::create('id_ID');
for($i = 1; $i <= 1000; $i++){
Employee::create([
'name' => $faker->name,
]);
}
}
}

Running faker and seeder.

php artisan db:seed --class=EmployeeSeeder

Integrating Select2 with Laravel

Firstly, ensure that you have Laravel installed and set up on your system. If not, you can easily install Laravel by following the official documentation.

Next, let’s integrate Select2 into our Laravel project:

  1. Integrating select2 with project using CDN.
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

2. Setting the controller, you can create EmployeeController.php

<?php
namespace App\Http\Controllers;
use App\Models\Employee;
use Illuminate\Http\Request;

class EmployeeController extends Controller
{
public function index()
{
return view('employee.index');
}

public function getEmployee()
{
$employees = Employee::all();
return $employees;
}
}

3. Setting route in web.php

Route::get('/employee', [App\Http\Controllers\EmployeeController::class, 'index']);
Route::get('/get-employee', [App\Http\Controllers\EmployeeController::class, 'getEmployee'])->name('get-employee');

Adding Loader Spinner with Input Select2

Now that we have integrated Select2 into our Laravel project, let’s proceed to add loader spinners to Input Select2 elements using AJAX.

  1. Create a Loader Spinner: Design a loader spinner using HTML and CSS. You can use existing libraries like Font Awesome for this purpose.
.loading {    
background-color: #ffffff;
background-image: url("{{ asset('img/spinner.gif') }}");
background-size: 25px 25px;
background-position:center center;
background-repeat: no-repeat;
}

2. Create form select to display data from database

<div class="container">
<div class="mt-5">
<div class="row">
<div class="col-4">
<label for="state">Employee</label>
<select class="form-control" id="employee" name="employee">
<option value='0'>Retrieving data...</option>
</select>
</div>
</div>
</div>
</div>

3. Get data from database with Ajax

<script>
async function myAsync () {
var employee = $('#employee');
$.ajax({
url: "{{ url('get-employee') }}",
type: "GET",
beforeSend: function () {
employee.addClass('loading');
},
success: function (data) {
employee.removeClass('loading');

employee.empty();
data.forEach(function(value) {
employee.append($("<option></option>").attr("value", value.id).text(value.name));
});
employee.select2();

},
complete: function () {
employee.removeClass('loading');
},
});
}

myAsync();
</script>

4. Full code

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Employee</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
.loading {
background-color: #ffffff;
background-image: url("{{ asset('img/spinner.gif') }}");
background-size: 25px 25px;
background-position:center center;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<div class="container">
<div class="mt-5">
<div class="row">
<div class="col-4">
<label for="state">Employee</label>
<select class="form-control" id="employee" name="employee">
<option value='0'>Retrieving data...</option>
</select>
</div>
</div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
async function myAsync () {
var employee = $('#employee');
$.ajax({
url: "{{ url('get-employee') }}",
type: "GET",
beforeSend: function () {
employee.addClass('loading');
},
success: function (data) {
employee.removeClass('loading');

employee.empty();
data.forEach(function(value) {
employee.append($("<option></option>").attr("value", value.id).text(value.name));
});
employee.select2();

},
complete: function () {
employee.removeClass('loading');
},
});
}
myAsync();
</script>
</body>
</html>

5. Final result

Process getting data with spinner
after result
After retrieving data from database

Conclusion

In conclusion, adding loader spinners to Input Select2 elements in your Laravel application with AJAX is a straightforward process. By following the steps outlined in this guide, you can enhance the user experience and create a more responsive web application. Implementing loader spinners not only improves visual aesthetics but also provides users with feedback during data loading processes, resulting in a smoother and more enjoyable browsing experience. So why wait? Implement loader spinners today and take your Laravel application to the next level!

--

--

Risqi Ahmad

I love to share about Web Development and Data Science