How to Load data using jQuery AJAX in Select2 – Laravel 8

How to Load data using jQuery AJAX in Select2 – Laravel 8

Select2 is easy to initialize on an element. It allows loading data with and without AJAX.

In this tutorial, I show how you can load MySQL database data in select2 using jQuery AJAX in the Laravel 8 project.


1. Database Configuration

Open .env file.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

2. Table structure

  • Create employees table using migration and add some records.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('username');
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created.

3. Model

Create Employees Model.

php artisan make:model Employees
  • Specify mass assignable Model attributes – username, name, and email using the $fillable property.

Completed Code

<?php

namespace App\Models;

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

class Employees extends Model
{
    use HasFactory;

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

4. Controller

Create a EmployeesController controller.

php artisan make:controller EmployeesController

Create 2 methods –

  • index() – Load index view.
  • getEmployees() – This method is used to handle AJAX requests.

Assign POST search value to $search variable.

If $search is empty then fetch 5 records from the employees table and assign to $employees otherwise, select 5 records where $search value exists in the name field using like.

Loop on the $employees and initialize $response Array with id and text keys.

Return $response in JSON format.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;

class EmployeesController extends Controller {

   public function index(){

     // Load index view
     return view('index');
   }

   // Fetch records
   public function getEmployees(Request $request){
      $search = $request->search;

      if($search == ''){
         $employees = Employees::orderby('name','asc')->select('id','name')->limit(5)->get();
      }else{
         $employees = Employees::orderby('name','asc')->select('id','name')->where('name', 'like', '%' .$search . '%')->limit(5)->get();
      }

      $response = array();
      foreach($employees as $employee){
         $response[] = array(
              "id"=>$employee->id,
              "text"=>$employee->name
         );
      }
      return response()->json($response); 
   } 
}

5. Route

  • Open routes/web.php file.
  • Define 2 routes –
    • / – Load index view.
    • /getEmployees – This is used to send AJAX POST request to fetch the employees list.
<?php 
use Illuminate\Support\Facades\Route; 
use App\Http\Controllers\EmployeesController; 

Route::get('/', [EmployeesController::class, 'index']); 
Route::post('/getEmployees', [EmployeesController::class, 'getEmployees'])->name('getEmployees');

6. View

Create a new index.blade.php file in resources/views/ folder.

HTML –

  • Stored CSRF token in the <meta > tag.
  • Include select2 and jQuery libraries.
  • Create a <select id='sel_emp' > element.

jQuery –

  • Read csrf_token from meta tag and assign to CSRF_TOKEN variable.
  • Initialize select2 on #sel_emp element.
  • Using 'ajax' option to send AJAX POST request to 'getEmployees'. Set dataType: 'json'.
  • With data pass the typed value and CSRF token as data – _token: CSRF_TOKEN, search: params.term.
  • Handle AJAX response with processResults. Initialize results with the response.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <title>How to Load data using jQuery AJAX in Select2 – Laravel 8</title>

   <!-- Meta -->
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <meta charset="utf-8">
   <meta name="csrf-token" content="{{ csrf_token() }}">

   <!-- CSS -->
   <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

</head>
<body>

   <!-- For defining select2 -->
   <select id='sel_emp' style='width: 200px;'>
      <option value='0'>-- Select employee --</option>
   </select>

   <!-- Script -->
   <script type="text/javascript">
   // CSRF Token
   var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
   $(document).ready(function(){

     $( "#sel_emp" ).select2({
        ajax: { 
          url: "{{route('getEmployees')}}",
          type: "post",
          dataType: 'json',
          delay: 250,
          data: function (params) {
            return {
               _token: CSRF_TOKEN,
               search: params.term // search term
            };
          },
          processResults: function (response) {
            return {
              results: response
            };
          },
          cache: true
        }

     });

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

7. Demo

View Demo


8. Conclusion

In the example, I set the limit to 5 while fetching records from the table. You can either remove it if you want to select all records or adjust it according to the requirement.

Select2 return response must have id and text keys otherwise, data would not load properly.

View this tutorial, to know selecte2 implementation in Laravel 7.



Comments