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.
CodePudding user response:
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);
});
CodePudding user response:
maybe your js is fetch url like
localhost/searchByName?search=abc
but route in php is defined is
localhost/searchByName/abc
It is diffirent .