2

I am implementing JQuery Select2() in my form. When I try to search, my ajax always returns 404 error. But the route exists in the web.php file.

Here is my code:

Web.php

Route::get('/searchByName/{var1}', [App\Http\Controllers\AppointmentsController::class, 'searchByName'])->name('searchByName');

JS File

$(document).ready(function() {

    url = $(".js-example-basic-single").attr('data-url');
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    $(".js-example-basic-single").select2({
        dropdownParent: $('.name-search-box'),
        language: {
            inputTooShort: function () {return "Plase enter minimum 3 caracteres";},
            minimumInputLength: function () {return "Plase enter minimum 3 caracteres";},
            noResults: function () {return "no results";}
        },
        minimumInputLength: 3,
        placeholder: "Select a patient",
        allowClear: true,
        width: "100%",
        debug: true,
        ajax: {
            type: "GET",
            url: "/searchByName",
            delay: 500,
            dataType: 'json',
            data: function (params) {
            var query = {
                search: params.term
            }

            // Query parameters will be ?search=[term]&type=public
            return query;
            },
            processResults: function (resp) { console.log('response' + resp);
                return {
                    results: resp
                }
            },
            cache: true
        }

    });

}

AppointmentsController.php

public function searchByName($var1){
    
        $key = $request->get('search');
        $name = DB::table('patients_tbl')->select('id', 'first_name', 'middle_name', 'last_name')
                ->where('first_name', 'LIKE', "%$key%")->get()->toArray();
        
        return $name;
    
}

I have tried route with and without parameters, cleared all types of cache including route cache etc but no use.

1
  • Your url is url: "/searchByName", but your route is '/searchByName/{var1}' you need to add your url to variable. Commented Nov 1, 2021 at 8:51

3 Answers 3

1

The route in your ajax file doesn't provide parameter. In url: "/searchByName" but in routes it has one parameter as {var1}

ajax: {
   type: "GET",
   url: "/searchByName",
   delay: 500,
   dataType: 'json',
   data: function (params) {
   var query = {
       search: params.term
}

Try this code once:

var uri = "{{ route('searchByName', ':variable') }}";
uri = uri.replace(':variable', var1);
$.ajax({
   url: uri,
   type: 'get',
   dataType: 'json',
   success: function(response) {
        console.log(response);
   });
0

maybe your js is fetch url like

localhost/searchByName?search=abc

but route in php is defined is

localhost/searchByName/abc 

It is diffirent .

0

I resolved the issue by changing method from GET to POST and adding _token with parameter in ajax function. Here is my corrected code

JS File

$(document).ready(function() {

    //var uri = "{{ route('searchByName', ':variable') }}";
    //uri = uri.replace(':variable', var1);
    //alert(uri);
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    $(".js-example-basic-single").select2({
        dropdownParent: $('.name-search-box'),
        language: {
            inputTooShort: function () {return "Plase enter minimum 3 caracteres";},
            //minimumInputLength: function () {return "Plase enter minimum 3 caracteres";},
            noResults: function () {return "no results";}
        },
        minimumInputLength: 1,
        placeholder: "Select a patient",
        allowClear: true,
        width: "100%",
        debug: true,
        ajax: {
            type: "POST",
            url: '/searchByName',
            delay: 500,
            dataType: 'json',
            data: function (params) {
            return {
                _token: CSRF_TOKEN,
                search: params.term // search term
                };
            },
            processResults: function (data) { console.log(data);
                return {
                    results: $.map(data, function(obj) {
                        return { id: obj.id, text: obj.first_name };
                    })
                };
            },
            cache: true
        }

    });

});

and web.php

Route::post('/searchByName', [App\Http\Controllers\AppointmentsController::class, 'searchByName'])->name('searchByName');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.