DEV Community

Sahil kashyap
Sahil kashyap

Posted on

2 1

Pagination in selectbox/dropdown, Optimal way to show large data in selectbox using select2

Select2 requires a response like this for pagination to work

{
  "results": [
    {
      "id": 1,
      "text": "Option 1"
    },
    {
      "id": 2,
      "text": "Option 2"
    }
  ],
  "pagination": {
    "more": true
  }
}
Enter fullscreen mode Exit fullscreen mode

we can generate this response by modifying the pagination in laravel

<?php

namespace App\Http\Controllers;

class SomeController extends Controller
{
   public function getdataforselect2(Request $request){

        if ($request->ajax()) {

            $term = trim($request->term);
            $posts = DB::table('channels')->select('id','name as text')
                ->where('name', 'LIKE',  '%' . $term. '%')
                ->orderBy('name', 'asc')->simplePaginate(10);

            $morePages=true;
           $pagination_obj= json_encode($posts);
           if (empty($posts->nextPageUrl())){
            $morePages=false;
           }
            $results = array(
              "results" => $posts->items(),
              "pagination" => array(
                "more" => $morePages
              )
            );

            return \Response::json($results);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
//api.php

Route::get('/tags', function() {
    return view('Somefolder.index');
});
Route::get('dataforselect2', 'SomeController@getdataforselect2')->name('dataforselect2');
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
  <div class="container">
  <div class="page-header">
    <h1>select2 with pagination</h1>
    </div>
    <select id='channel_id' style='width: 200px;'>
        <option value='0'>- Search Channel -</option>
     </select>
    </div>
    <script type="text/javascript" src='//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
    <!--<![endif]-->
    <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> <script >

(function() {

  $("#channel_id").select2({
    placeholder: 'Channel...',
    // width: '350px',
    allowClear: true,
    ajax: {
        url: '/dataforselect2',
        dataType: 'json',
        delay: 250,
        data: function(params) {
            return {
                term: params.term || '',
                page: params.page || 1
            }
        },
        cache: true
    }
});
})();

    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

gist of all the code

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay