jQuery.Deferred exception: Cannot read properties of undefined (reading 'length') -> Laravel 8 Boilerplate + Bootstrap

Viewed 2957

I am using Laravel Boilerplate from Sebastien Heyd and trying to get Select2 options via Ajax. When I click on the select element after the page loads, I get the error:

jQuery.Deferred exception: Cannot read properties of undefined (reading 'length') TypeError: Cannot read properties of undefined (reading 'length').

Error in browser console.

My code is like this.

  1. Blade template.

        <div class="col-lg-2">
        <div class="form-group">
                <x-boilerplate::select2 name="frm_Daily_Heading" id="frm_Daily_Headings" label="Heading" :ajax="route('boilerplate.getHeadings')" :allowClear="true" placeholder="-">
                </x-boilerplate::select2>
        </div>
    </div>  
    
@endsection
@include('boilerplate::load.select2')
@include('boilerplate::load.datepicker')
@push('js')

    <script>    
    $( document ).ready(function() {
        $( "#frm_Daily_Headings" ).select2({
            ajax: { 
                url: "{{route('boilerplate.getHeadings')}}",
                type: "post",
                dataType: 'json',
                delay: 2500,
                data: function (params) {
                    if(params.term === undefined){return} else{
                    return {
                        q: params.term, // search term
                        "_token": "{{ csrf_token() }}",
                    };}
                },
                processResults: function (response) {
                    if(results === undefined) {return} else {
                    return {
                        results: data.items
                        // id: params.term,
                        // text: params.term
                        // newOption: true
                    };}
                },
                cache: true
            }
        });
    });
    $('.datepicker').datetimepicker();
</script>

    @endpush
```
  1. My Controller for handling Ajax request for the Select2.

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Models\heading;
    
    class HeadingsController extends Controller
    {
        public function index() {
            return view('daily');
        }
        public function getHeadings(Request $request)
        {
            $input = $request->all();
            if (!empty($input['query'])) {
                $data = heading::select(["id", "heading"])
                ->where("heading", "LIKE", "%{$input['query']}%")
                ->get();
            }
            else
            {
                $data = heading::select(["id", "heading"])->get();
            }
            $headings = [];
            $returnThis=[];
            if (count($data) > 0)
            {
                foreach ($data as $heading)
                {
                    $headings[] = array(
                        "id" => $heading->id,
                        "text" => $heading->heading,
                    );
                    $returnThis=['results',$headings];
                }
            }
            return response()->json($returnThis);
        }
    }
    
  2. My Model

    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use App\Http\Controllers\HeadingsController;
    
    class heading extends Model
    {
        use HasFactory;
        protected $fillable=['id','heading'];
    }
    

When I click on the dropdown, I get the above error. However, using the dev tools in chrome, under the Network section, I can see the values being loaded. Ajax response in Chrome dev tools

The Ajax response corresponds to the requirements in Select2 documentation.

My jquery is being loaded before bootstrap.min.js.

All scripts and Laravel are the up to date versions.

Any help would be greatly appreciated.

Cheers.

1 Answers

I am the author. I've just seen your question.

The component <x-boilerplate::select2 /> generate his own js call when you set the attribute :ajax, you don't have to write your own.

If you want to use your own script to generate a select2 you have to use the component <x-boilerplate::input type="select" /> and apply your script to it.

I think your error is in the controller : $returnThis=['results' => $headings]; instead of $returnThis=['results',$headings];

In any case, thanks for using my package!

Related