How To Dynamicaly Load Data in Select2 Using AJAX in PHP Laravel
Nov
18

How To Dynamicaly Load Data in Select2 Using AJAX in PHP Laravel

Select2 is a popular jQuery-based library that transforms standard HTML select elements into powerful, feature-rich dropdowns. When combined with AJAX in a Laravel application, it can provide a smooth user experience.

Let's break down the key components to implement it:

Frontend (JavaScript using jQuery and Select2)

The front-end code initializes a Select2 dropdown on an ID element "location-id." Here are some of the important configurations:

Here is Select input we will use.

  <div class="form-group">
    <label for="location-id">Locations</label>
    <select class="form-control select2" id="location-id">
    </select>
  </div>
  • Minimum Input Length: Users must enter at least 3 characters before triggering a search.
  • AJAX Configuration: The dropdown fetches location data dynamically using AJAX.
  • url: "{{ route('locations-ajax') }}"

    • Specifies the URL where the AJAX request will be sent.
  • dataType: "json"

    • Indicates that the expected data type of the response is JSON.
  • delay: 250

    • Introduces a delay of 250 milliseconds before sending the AJAX request. This helps prevent sending too many requests in a short period, providing a brief pause to allow the user to finish typing.
  • data: function (params) { ... }

    • Defines a function that returns the data to be sent with the AJAX request. In this case, it sends the user's input (params.term) as the 'name' parameter in the request. This parameter is used by the server-side logic to filter and fetch relevant location data.
  • processResults: function (data) { ... }

    • Defines a function that processes the results received from the server. It maps the data received to a format that Select2 expects, with each item having 'text' and 'id' properties.
  • cache: true

    • Enables caching of AJAX responses, enhancing performance by storing and reusing previously fetched data. This can be particularly beneficial when the user repeats similar queries.

 

$("#location-id").select2({
    minimumInputLength: 3,
    ajax: {
        url: "{{route('locations-ajax')}}",
        dataType: "json",
        delay: 250,
        data: function (params) {
            return {
                name: params.term
            };
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.text,
                        id: item.id
                    }
                })
            };
        },
        cache: true
    },
    placeholder: "Please type location name...",
    escapeMarkup: function (markup) {
        return markup;
    }
});

Backend (Laravel Controller and Route)

On the Laravel side, a route is defined to handle AJAX requests for fetching location data. The route points to the LocationAjax method in the LocationController. This method uses the Location model to retrieve relevant data based on the user's input.it could be any Model.

// Route definition
Route::get('location-ajax', [LocationController::class, 'LocationAjax'])->name('location-ajax');

// Controller method
public function locationAjax(Request $request)
{
    $name = trim($request->name);
    $locations = Location::select(['locations.id as id', 'locations.name as text'])
        ->where('locations.name', 'LIKE', "%{$name}%")
        ->limit(5)
        ->get();

    return response()->json($locations->toArray());
}

In summary, this integration allows users to search and select dynamically, enhancing the overall user experience by minimizing manual effort and providing real-time results. The combination of Select2 and Laravel's AJAX functionality creates a smooth and efficient selection process.

 

 

Contact

Get in touch with us

Feel free to request missing tools or give some feedback.

Contact Us