Select2 getting 400 Bad Request


I keep getting [term] in my querystring resulting in a 400 bad request.

Any help is appreciated

The string looks like


bud should look like


In my helper file i have

    public static function brandbyid($id=1) {


        $sql =    'SELECT id, brand  '

                . 'FROM brand '

                . 'WHERE id="'.$id.'" ';


        $brand = Brand::findBySql($sql)->asArray()->all();

        return $brand;


in my _form I use

$url = \yii\helpers\Url::to(['/site/brandlist']);

/* @var $this \yii\web\View */

/* @var $content string */

// Script to initialize the selection based on the value of the select2 element

$initScript = <<< SCRIPT

    function (element, callback) {

        var id=\$(element).val();


        if (id !== "") {


            \$.ajax("{$url}?id=" + id, {

                dataType: "json"

            }).done(function(data) { callback(data.results);});




An the form field

    <?= $form->field($model, 'id')->widget(Select2::classname(), [

                'options' => ['placeholder' => 'Search for a brand ...'],

                'pluginOptions' => [

                    'allowClear' => true,

                    'minimumInputLength' => 2,

                    'ajax' => [

                        'url' => $url,

                        'dataType' => 'json',

                        'data' => new JsExpression('function(term,page) { return {search:term}; }'),

                        'results' => new JsExpression('function(data,page) { return {results:data.results}; }'),



                    'initSelection' => new JsExpression($initScript)



Hi there,

I lost an hour on this one end of last week. Prototype of function has changed a bit: Change

'data' => new JsExpression('function(term,page) { return {search:term}; }')


'data' => new JsExpression('function(params) { return {search:params.term}; }')

Please also note that the generated hidden field in html form is no longer an input but a select.


Yes it works!! no more errors…

Except results are not showing.

Do I have to make there a change as well?

'results' => new JsExpression('function(data,page) { return {results:data.results}; }'),

No, I haven’t changed that, but it depends on what your php returns.

The jsonified php associative array has to match your javascript object.

To debug, try to call the url in a browser or in a browser inspector. You’ll see the problem right away.

Like I explained in the note, Select2 has also changed the html. I relied on a input (type=hidden) before, but Select2 is not a html select.

So I had to adjust that as well, but it is not related to the json JS used to parse the return value.