Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

relaxandwork's avatar

Select2 ajax on Laravel

Hi, has anyone successfully integrated Select2 on Laravel5 ? This is with ajax. I almost got it to work, the only problem I am having right now is on the part of processing results. This is the json output:

[
    {
        "id": "43affe22-df76-11e4-b2e5-00e040016184",
        "name": "beer"
    },
    {
        "id": "ec6339da-df76-11e4-83d3-00e040016184",
        "name": "Beers"
    }
]

And this is my js script:

$('#tag_list').select2({
            placeholder: 'Enter a tag',
            ajax: {
                dataType: 'json',
                url: '{{ url("api/tags") }}',
                delay: 400,
                data: function(params) {
                    return {
                        term: params.term
                    }
                },
                processResults: function (data, page) {
                  return {
                    results: data
                  };
                },
            }
});

Or is it my json that is wrong?

0 likes
11 replies
relaxandwork's avatar
relaxandwork
OP
Best Answer
Level 1

Solved it. The json must return [{"id": "value", "text":"value"}] format.

3 likes
j-cart's avatar

Hi. I'm trying to implement select2 as well, but am a noob and having all sorts of troubles. Can you show me what your blade code for this looks like?

I'm not sure what to initially pass to the view from the controller, as a select form expects an array, but I don't have one before the user starts typing/the AJAX request is made?!

For example, at the moment I'm passing an array of Units as $units from the controller:

[Controller]
return view('movements.movements')->with(['units_in' => $units_in , 'units_out' => $units_out, 'yards' => $yards, 'units'  => $units]);

[View]
{!! Form::label('unit_id_in', 'Unit ID:') !!}
 {!! Form::select('unit_id_in', $units, null, ['class' => 'form-control', 'id' => 'select2']) !!}

but if I don't create the array $units and pass it to the view, obviously Laravel has a fit (undefined variable)! Please tell me, what do I put in place of $units in my blade form declaration as a placeholder for the select2 AJAX call???

aardalich's avatar

Sounds fine to me, either pass an empty array from the controller, or simply replace $units in your view with [] if the select2 control is getting it's source from ajax.

j-cart's avatar

Thanks for the reply, @aardalich, but I only just figured it out - the form element must be type hidden, as in:

 {!! Form::hidden('unit_id_in', null, ['class' => 'form-control', 'id' => 'select2']) !!}
aardalich's avatar

hmm, not in what I've been working on the past couple of weeks.

It could be I'm using the current release where I think from memory older versions of select2 required a hidden element.

relaxandwork's avatar

@joshcarton This is what's on my blade

    <div class="form-group">
        {!! Form::label('tag_list') !!}
        {!! Form::select('tag_list[]', $tags, null, ['class' => 'form-control', 'id' => 'tag_list', 'multiple']) !!}
    </div>

The values of tag_list is coming from my Article model:

/**
 * Get a list of tag ids associated with the article.
 *
 * @return array
 */
 public function getTagListAttribute()
 {
        return $this->tags->lists('name');
 }

Make sure your ajax return the same format I mentioned earlier in this thread.

mafisz's avatar

I've got problem with select2 too. Error was "Cannot read property 'slice' of undefined".

Solution that is working for me was adding "results" in the begining of the json response:

$users = User::get();
        foreach ($users as $key => $value) {
            $list[$key]['id'] = $value->id;
            $list[$key]['text'] = $value->name; 
        }

        return "{ \"results\": " . json_encode($list) . "}"; 
lorvent's avatar

I am getting results properly

but not able to show them inside select2 options

sometimes, dropdown click, its auto closing dropdown and if i click on it again, its showing all the results

but thats not a good UX.

phpMick's avatar

When I try this :

$('.js-data-example-ajax').select2({
            placeholder: 'Enter a tag',
            ajax: {
                dataType: 'json',
                url: '{{ url("api/tags") }}',
                delay: 400,
                data: function(params) {
                    return {
                        term: params.term
                    }
                },
                processResults: function (data, page) {
                    return {
                        results: data
                    };
                },
            }
        });
'

The search term still goes in the GET:

/api/tags?term=1

what I really want is :

/api/tags/1

Has anyone managed to do anything like this?

Mick

1 like
phpMick's avatar

Just hacked it (horribly) like this:

Route::get('getProducts', function(){

$term = Input::get('term');

//dd($term);

return Redirect::action('AjaxController@getProducts', compact('term'));

});

1 like

Please or to participate in this conversation.