how to create relational select option ajax in laravel 8 - ajax

I try to create a relational select option in laravel 8 using ajax but didn't work I get this error in the console: 405 Method Not Allowed
POST http://127.0.0.1:8000/decomptes/%7B%7B%20route(%20'getOperationsChantier'%20)%20%7D%7D 405 (Method Not Allowed)
the route
Route::post('/getOperationsChantier', [DecompteController::class, 'getOperationsChantier'])->name('getOperationsChantier');
the jquery code
$(document).ready(function(){
// When an option is changed, search the above for matching choices
$('#chantiers').change(function(){
$("#mySelect option").remove();
// $("#city option").remove();
var id = $(this).val();
$.ajax({
url : "{{ route( 'getOperationsChantier' ) }}",
data: {
"_token": "{{ csrf_token() }}",
"id": id
},
type: 'post',
dataType: 'json',
success: function( result )
{
$.each( result, function(k, v) {
$('#mySelect').append($('<option>', {value:k, text:v}));
});
},
error: function()
{
//handle errors
alert('error...');
}
});
}).change();
});
the function in the controller :
function getOperationsChantier( Request $request )
{
$this->validate( $request, [ 'id' => 'required|exists:chantiers,id' ] );
$chantierOperations = ChantierOperation::where('chantier_id', $request->get('id') )->get();
$output = [];
foreach( $chantierOperations as $chantierOperation )
{
$output[$chantierOperation->id] = $chantierOperation->operation_id;
}
return $output;
}
can someone help me this is the first time when I use ajax

Related

How to set selected value in edit mode - Select2 with AJAX Remote Data

Please wait, I know you will say that this is a possible Duplicate. The answer is Yes.
Here's the link
But none of the answers works for me.
On my blade I put the value in a hidden input field.
<input type="hidden" value="{{ $recipe->cuisine_type_id }}" id="selectedCuisineTypeId">
I have the same scenarios. Here's my JS;
var selectedCuisineTypeId = $("#selectedCuisineTypeId").val();
$('#cuisine_type_id').val(selectedCuisineTypeId).trigger('change');
$( "#cuisine_type_id" ).select2({
ajax: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
placeholder: "Select Cuisine",
url: "{{ route('ajax-cuisine-search') }}",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
Why it is not working for me? What did I miss?
I have solved my issue above. Here's what I did.
Make a hidden field of the ID you want to get selected and set a variable for it.
<input type="hidden" value="{{ $recipe->cuisine_type_id }}" id="selectedCuisineTypeId">
Create a new route to fetch the selected value and trigger Select2.
Route
Route::get('recipe/cuisine/{id}', [SearchController::class, 'getSelectedCuisine'])->name('getSelectedCuisine');
Controller
*selectCuisineSearch class to load the list of Cuisines.
getSelectedCuisine class to fetch the selected Cuisine in Edit Mode
public function selectCuisineSearch(Request $request)
{
$search = $request->search;
if ($search == '') {
$cuisines = Cuisine::orderby('name', 'asc')->select('id', 'name')->get();
} else {
$cuisines = Cuisine::orderby('name', 'asc')->select('id', 'name')->where('name', 'like', '%' . $search . '%')->limit(5)->get();
}
$response = array();
foreach ($cuisines as $cuisine) {
$response[] = array(
"id" => $cuisine->id,
"text" => $cuisine->name
);
}
return response()->json($response);
}
public function getSelectedCuisine(Request $request)
{
$cuisineId = $request->id;
$cuisines = Cuisine::where('id', $cuisineId)->first();
$response = array(
"id" => $cuisines->id,
"name" => $cuisines->name
);
return response()->json($response);
}
On my Edit Blade
$(document).ready(function(){
$( "#cuisine_type_id" ).select2({
ajax: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
placeholder: "Select Cuisine",
url: "{{ route('ajax-cuisine-search') }}",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
search: params.term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
var selectedCuisineTypeId = $("#selectedCuisineTypeId").val();
var cuisineSetSelected = $('#cuisine_type_id');
$.ajax({
type: 'GET',
url: '{{ route('getSelectedCuisine')/' + selectedCuisineTypeId
}).then(function (response) {
var option = new Option(response.name, response.id, true, true);
cuisineSetSelected.append(option).trigger('change');
cuisineSetSelected.trigger({
type: 'select2:select',
params: {
results: response
}
});
});
});
This solution might be long. You are free to suggest making this shorter. I am happy to learn more. Cheers!

Laravel Explode Ajax Request Containing Name and Numbers

I'm using laravel 8.4 .
My route :
Route::post('test',[\App\Http\Controllers\DataController::class, 'store'])->name('pos-test');
My Controller :
public function store(Request $request)
{
// DB::table('data')->insert('product_code',$request->id);
$badge = explode(' ', $request);
$employee_id = $badge[0];
\DB::table('data')->insert(['product_code'=> $employee_id]);
return response()->json(['success'=>'Product saved successfully.']);
}
Ajax code :
function handleBarcode(scanned_barcode) {
//handle your code here....
console.log(scanned_barcode);
let _token = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('pos-test') }}",
type: "POST", // Can change this to get if required
data: {
code : scanned_barcode,
_token: _token
},
success: function(data) {
$("#status").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#status").text(textStatus);
console.log(jqXHR);
}
});
};
The request is like this "555444 Razif Raziq" , i would like to explode it so I may insert only "555444" into table but in table column product_code is 'POST' .
The question is how to fix it? thank you
you must explode your correct data in request object not request object itself.
$badge = explode(' ', $request->code);
If the 'code' value is sent correctly, just use this
$request->code
public function store(Request $request)
{
\DB::table('data')->insert(['product_code'=> $request->code]);
return response()->json(['success'=>'Product saved successfully.']);
}

Ajax update field database field in laravel blade template

I have a list of hotels in a select I want update the database base on the hotel selected if it update the field I want to alert it on the home page.
this is the ajax function
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});
}
}
my controller
public function update(Request $request, $hotel_plan_id)
{
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}
my route
Route::post('home/{hotel_plan_id}', 'HomeController#update')->name('home');
my select form
{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}
You have error with ajax url and you dont also pass the value of hotel name.
Check this changes.
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}
Please return json response
return response()->json();
You have to return json object like this
return response->json([
'status' => 200,
'result' => true,
'error' => false,
'data' => $hotel
]);

Datatables won't work with ajax POST type and GET type

I used GET method first and I would get this error:
414 (Request-URI Too Long)
My ajax is like this:
var table = $('#datatable').DataTable( {
stateSave: true,
scrollX: true,
serverSide: true,
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
type: 'GET',
data: function ( d ) {
d.zakljucano = $('#zakljucano').val();
},
},...
And my route:
Route::get('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
But then i get error: 414 (Request-URI Too Long)
If i switch to POST type adn switch my route to post i will get this error:405 (Method Not Allowed)
var table = $('#datatable').DataTable( {
stateSave: true,
scrollX: true,
serverSide: true,
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
type: 'POST',
data: function ( d ) {
d.zakljucano = $('#zakljucano').val();
},
},...
And my POST route:
Route::post('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
My controller
public function tabela_evidencije(Request $request, $id, $tip)
{
$evidencija = EvidencijaRadnikaPoDanu::with('radnik', 'radnik.identifikacija')
->select('evidencija_radnika_po_danus.*', 'radniks.id_identifikacije')
->where('evidencija_radnika_po_danus.id_kompanije', Auth::user()->id_kompanije)
->where('evidencija_radnika_po_danus.id_radnih_dana', $id)
->where('evidencija_radnika_po_danus.tip', $tip);
return datatables()->of($evidencija)
->editColumn('id_radnika', function ($data) {
$puno_ime = $data->radnik->prezime.' '.$data->radnik->ime;
return $puno_ime;
})
->editColumn('id_ime', function ($data) {
return $data->radnik->ime;
})
//pomocu veze izmedju radnika i evidencija pronalazimo identifikacioni broj
->editColumn('id', function ($data) {
return $data->radnik->identifikacija->broj;
})
->editColumn('id_radnika_modal', function ($data) {
return $data->id_radnika;
})
->editColumn('id_modal', function ($data) {
return $data->id;
})
->make(true);
}
After inspecting it while using GET my URL is over 8,000 characters!
I added in my <head> this:
<meta name="csrf-token" content="{{ csrf_token() }}">
and added token in my ajax POST method
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
method: 'POST',
'headers': {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}...
And also changed my route to be post
Route::post('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
And i had to run this command in my console
php artisan optimize
In order for my route to change to POST route...

Delete a row from the database via ajax

I have this javascript function to delete the row but the function is not working
$(document).ready(function()
{
$('table#example td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "supprimerkpi",
data: data,
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
// sets specified color for every odd row
$('table#example tr:odd').css('background',' #FFFFFF');
}
});
}
});
and in my page html:
<a href="#" class="delete" style="color:#FF0000;">
in my controller
$repository = $this->getDoctrine()->getEntityManager()->getRepository('AdminBlogBundle:Condkpi'); $id=$this->getRequest()->query->get('id');
$em = $this->getDoctrine()->getEntityManager();
$uti=$repository->findOneBy(array('id' => $id));
$em->remove($uti);
$em->flush();
You are sending the "id" via POST method. So, you need to change:
$id=$this->getRequest()->query->get('id');
into:
$id=$this->getRequest()->request->get('id');
Also, you could change:
$uti=$repository->findOneBy(array('id' => $id));
into:
$uti=$repository->find($id);
.. as find() searches entity using the primary key...
On a side note, what is "supprimerkpi"? That can't be a valid destination URL, right? :)
In your routing.yml
delete_data:
path: /delete
defaults: { _controller: AcmeDemoBundle:Default:delete}
in your ajax call url parameter change that according to this
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "{{ path('delete_data') }}",
data: {id :id },
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
// sets specified color for every odd row
$('table#example tr:odd').css('background',' #FFFFFF');
}
});
in your AcmeDemoBundle/Controller/DeafultControlller.php
public function deleteAction(Request $request)
{
$id = $request->get('id');
$repository =
$this->getDoctrine()->getEntityManager()->getRepository('AdminBlogBundle:Condkpi');
$em = $this->getDoctrine()->getEntityManager();
$uti=$repository->findOneById($id);
$em->remove($uti);
$em->flush();
}

Resources