Select2 ajax example

  • 28-12-2022
  • 567
  • Laravel 9
  • Haresh Chauhan

Complete the dynamic select2 tutorial with the help of ajax and laravel in this post I will teach you how to add the autofill dropdown add in any HTML from, In this example, i will tell you how to add select2 dynamic autofill dropdown and how to add in in the form.

For adding the select2 dynamic data dropdown using ajax we will first import the stylesheet CDN library the make it stylish, we will also add a script link for the run select() method from the core js select2 library.

Select2 gives us a customized select box with the support of helping searching, tagging, and dynamically remote data set using ajax, also provided infinity scrolling as well we many highly used option provided by select2. this is a very simple step for the integrating in your application.

Follow the below step for adding the select2 dynamic searching data autofill dropdown using external API data. so let's start with the first step of importing CDB in the HTML document.

Step 1. Import Library

Supporting select2 with the CDN is the fastest way to get up and running Select2 Select2 is available in both terms Select2 jsDelivr and cdnjs CDNs. simple and run fasted way add in your head tag to the web page.

<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>

Step 2. Select Tag

<select class="form-control select2"></select>

In the select2() method we will define ajax simply, using ajax we will call backed API for getting data dynamic data resources from the database server, for taking making API endpoint, I am taking laravel server-side script for the find location matched string from the database.

Once you search on the select box it will send the searching string request to the API for the find matching string, we will send data in terms veriable using the GET method.

the processResults() method will return success response form the API, we will map the API response data and append in the option tag, the option tag with value attribute that we don't need to do that since we are using select2 CSS library, it will add itself from the library.

$(".select2").select2({
     ajax: {
          url: "{{ route('api.customer.address') }}",
          dataType: 'json',
          type: "GET",
          quietMillis: 50,
          data: function (term) {
               return {
                    term: term
               };
          },
          processResults: function (data) {
               return {
                    results: $.map(data.data, function (item) {
                         return {
                              text: item.location,
                              id: item.id
                         }
                    })
               };
          }
     }
});

Step 3. API Laravel

Using laravel, create an API route for the add endpoint in the ajax URL.

routes/api.php
use App\Http\Controllers\CustomerAddressController;

Route::get('customer-address',[CustomerAddressController::class,'customerAddressLocation'])->name('api.customer.address');

Once you search in the select dropdown it will come here for the search in the server database and the after-like matching work query will find from the database and the matching string will return to the API. I just add a simple laravel controller method just for better understanding purposes only.

App\Http\Controllers\CustomerAddressController.php
use App\Models\Pincode;

public function customerAddressLocation(Request $request)
{
     $locations = Pincode::where('delivery','yes')
          ->select('location','id')
          ->when(isset($request['term']['term']),function($query) use ($request){
               $query->where('location','like',"%{$request['term']['term']}%");
          })
          ->paginate(20);

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

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :