Laravel: Passing selected values to route function from dropdown selection - php

I have a dropdown list that I want to be able to select a value and modify a value in the MYSQL table by calling a function on change.
The drop list is created with:
<td>
{{-- {{ $ticket->priority}} --}}
<div class="form-group{{ $errors->has('priority') ? 'has-error': '' }}">
<div class="col-md-6">
<select id="priority" type="" class="form-control" name="priority"
onchange="{{ url('admin/updatePriority/',['ticket_id' => $ticket->ticket_id, 'priority'=> value ] )}}">
<option value="">{{ $ticket->priority}}</option>
<option value="Low">Low</option>
<option value="Moderate">Moderate</option>
<option value="High">High</option>
</select>
</div>
</div>
</td>
The function in the Routes is:
Route::group(['prefix' => 'admin', 'middleware' => 'admin'], function () {
Route::get('tickets', 'TicketsController#index');
Route::post('close_ticket/{ticket_id}', 'TicketsController#close');
Route::post('updatePriority/{ticket_id}/{priority}', 'TicketsController#updatePriority');
});
The code for the function is:
public function updatePriority($ticket_id, $priority)
{
$ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail();
$ticket->priority = $priority;
$ticket->save();
}
When I make a selection from the dropdown box, the onchange function is not triggered, so the value remains unchanged in the table.
Can anyone point me in the right direction on this?

HTML event listeners expect Javascript code or function calls, a URL is not valid in such context
Here's what you can do
<td>
<div class="form-group{{$errors->has('priority') ? 'has-error': '' }}">
<div class="col-md-6">
<select id="priority" type="" class="form-control" name="priority" onchange="change({{ $ticket->ticket_id }}, this.value)">
<option value="">{{ $ticket->priority}}</option>
<option value="Low">Low</option>
<option value="Moderate">Moderate</option>
<option value="High">High</option>
</select>
</div>
</div>
</td>
<script>
function change(ticket_id, priority) {
const response = fetch('/admin/updatePriority/' + ticket_id + '/' + priority, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": document.head.querySelector('meta[name="csrf-token"]')
},
method: "post",
});
console.log(JSON.stringify(response));
}
</script>
This is using the native Ajax fetch API to perform the request to the URI with the dynamically changed value of the select element as parameter
Note that you still need to deal with CSRF header and to properly call the parameters in the controller from the request object
Hope this helps

Related

Dynamic Dependent Drop down selection in Laravel

HI everyone I'am working on dynamic dependent dropdown selection but i can't achieve the required output , when i select something in column of the State , column of the city stay always empty .
This is my controller specvil.php:
public function index () {
$ville=Vil::orderBy('Ville','desc')->get();
return view ('index',['vi'=>$ville]);
}
public function deleg(Request $request)
{
$delegation = DB::table("delegation")
->where("ville_id",$request->ville_id)
->pluck("ville","id");
return response()->json($delegation);
}
And this is the view of the form index.php:
<form action="{{route('ghof')}}" method="get">
{{ csrf_field() }}
<select type="text" class="search-field location" name="spec" id="s"
value="spec" placeholder ="Spécialités">
<option selected></option>
#foreach($sp as $ss)
<option value=" {{$ss->Spécialité}}"> {{$ss->Spécialité}}</option>
#endforeach
</select>
<select type="text" class="search-field location" name="Région" id="Région"
value="Région">
<option selected></option>
#foreach($vi as $vv)
<option value="{{$vv->Ville}}">{{$vv->Ville}}</option>
#endforeach
</select>
<select type="text" class="search-field location" name="ville" id="ville">
</select>
<button class="search-btn" type="submit" id="search"> Recherche </button>
</div>
</form>
This is the script :
<script type="text/javascript">
$('#Région').change(function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:"GET",
url:"{{url('deleg')}}?ville_id="+countryID,
success:function(res){
if(res){
$("#ville").empty();
$("#ville").append('<option>Select</option>');
$.each(res,function(key,value){
$("#ville").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#ville").empty();
}
}
});
</script>
and finaly this is the route :
Route::get('/index','specvil#index');
Route::get('deleg','specvil#deleg');
Maybe this is the problem. You are passing Ville desc as an option value instead of passing Ville id which then causes you to match Ville desc to Ville id in deleg() method of your controller.

Fill select box from other vuejs laravel axios

I have two tables, SALARIE and CHANTIER, between them the relationship hasMany BelongsTTO, chantier1 (salarie1, salarie2, salarie3...), in my blade I have two selections, I want when I choose in select 1(chantier) to the the 2nd select(salaries) fill in with salaries of Chantier chosen.
SalarieController
public function pointage()
{
$chantiers = Chantier::all();
return view('pointage', ['chantiers' => $chantiers]);
}
pointage.blade.php
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<div class="form-group ">
<label>chantier:</label>
<select class="form-control" #change="onChange">
#foreach($chantiers as $chantier)
<option value="{{ $chantier->id }}">{{ $chantier->nomC }} {{ $chantier->id }}</option>
#endforeach
</select>
</div>
<div class="form-group ">
<label>salarie:</label>
<select class="form-control" #change="onChange">
#foreach($salaries as $salarie)
<option value="{{ $salarie->id }}">{{ $salarie->nomS }} </option>
#endforeach
</select>
</div>
</div>
vuejs code
const app = new Vue({
el: "#app",
data: function() {
return {
message: "Vue"
}
},
methods: {
onChange(event) {
}
}
})
Route
Route::get('pointage', 'SalarieController#pointage');
You can define computed variable salaries and on chantiers changes make request and if done fill salaries with response data and instead of using laravel's for each use v-for="salary in salaries.
Hope it help u.

Redirect selected option on submit laravel

How can I redirect my selected option when I click submit?
I am trying to make a modal Sign Up that is located in the header for different users. When the user choose one, they will then be redirected to specific sign up page.
This is from my header.blade.php
<div id="modal1" class="modal">
<div class="modal-content">
<h4>Choose Roles/Plan</h4>
<div class="input-field col s12">
<select id="select-action" name = "action">
<option value="" disabled selected>Choose your option</option>
<option value="basicsignup">Basic</option>
<option value="advancedsignup">Advanced</option>
<option value="teamsignup">Team</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="submit">Submit</button>
</div>
</div>
routes.php
Route::get('/basicsignup', function(){
return view('actions.basicsignup');
})->name('basicsignup');
Route::get('/advancedsignup', function(){
return view('actions.advancedsignup');
})->name('advancedsignup');
Route::get('/teamsignup', function(){
return view('actions.teamsignup');
})->name('teamsignup');
Edit: Original examples were animals, flowers, cars.. edited it for clarity at least.
You can simply use JavaScript onsubmit function to call a JS function than get your selected value and then you can submit a form with your customised url.
Example
<form method="post" id="myForm" onsubmit="return submitForm()">
<select id="select-action" name="action">
<option value="" disabled selected>Choose your option</option>
<option value ="animals">Animals</option>
<option value ="flowers">Flowers</option>
<option value ="cars">Cars</option>
</select>
<button type="submit">Submit</button>
</form>
<script type="text/javascript">
function submitForm() {
var selectedOption = $('#select-action').val();
var url = "";
if(selectedOption == 'animals') {
url = '{{ route('your/route')}}';
} else if (selectedOption == 'flowers') {
url = '{{ route('your/route')}}';
}
.
.
.
$('#myForm').attr('action', url);
$('form#myForm').submit();
return false;
}
</script>

Laravel AJAX form (receiving data concern)

I have an issue recieving the data from a form which was modified with AJAX.
I have 2 fields: Cinema and Session.
The Session field updates automatically based on which cinema you have chosen. However, when I try to get the session field's value in my controller, it returns as "" (blank) where-as I want it to return what is actually displayed in the drop down box in the form.
Code:
Script:
<script>
$('#cinema').on('change', function(e){
console.log(e)
var cinema_id = e.target.value;
//ajax
$.get('{{ url('/ajax-subcat') }}?cinema_id=' + cinema_id, function(data){
//success data
console.log(data)
$('#sesh').empty();
$.each(data, function(index, subcatObj){
$('#sesh').append('<option value="'+subcatObj.id+'">'+subcatObj.session_time+'</option>');;
});
});
});
</script>
Controller:
public function cart()
{
$formData = array(
'cinema' => Input::get('cinema'),
'sesh' => Input::get('sesh'),
'ticketType' => Input::get('ticketType'),
'count' => Input::get('count')
);
$cinemaDetails = Cinema::find($formData['cinema']);
$session = Session::find($formData['sesh']);
return view('movies/ticketpage/cart')
->with('formData', $formData)
->with('cinemaDetails', $cinemaDetails)
->with('session', $session);
}
View/Blade file:
<div class="container">
<div class="row">
<div class="col-sm-4">
<h2>{{$movie->title}}</h2>
<img src="/WDAAssign2/Assign2-A/{{ $movie->image }}" height="200" width="150">
<p>{{ $movie->description }}</p>
</div>
<div class="col-sm-4">
<h2>Purchase tickets!</h2>
{!! Form::open(array('action'=>'MoviePageController#cart', 'files'=>true)) !!}
<label>Select a Cinema:</label><br>
<select id = "cinema" name = "cinema">
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
</select>
<br>
<label>Select a session:</label>
<br>
<select id = "sesh" name = "sesh">
<option value=""></option>
</select>
<br>
<label>Type of ticket:</label>
<br>
<select id= ="ticketType">
<option value="adult">Adult</option>
<option value="concession">Concession</option>
<option value="children">Children</option>
</select>
<br>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
#for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
#endfor
</select>
<br><br>
<input type="submit" value="Submit">
{!!Form::close()!!}
</div>
</div>
</div>
Routes:
Route::post('/movie/ticketpage/cart', 'MoviePageController#cart');

dropdown show right value

ve two values in my combo box. Car and bicycle when the user selects one of them it will be stored in the database with 1 or 2. But how do I make sure that when the user edits it the chosen values shows up.
For example I've saved bicycle in the database than when the user wants to edit it it must show bicycle and not car!
I'm working with laravel.
EDIT
<div class="form-group">
<label for="content" class="col-lg-2 control-label">Standaard route</label>
<div class="col-lg-10">
#if($standaardroute->isEmpty())
<label>U heeft nog geen standaardroutes. Maak deze hier aan.</label>
#else
<select class="form-control input-sm" name="standaardroute" id="standaardroute">
#foreach($standaardroute as $route)
<option value="{!! $route->id !!}">{!! $route->van !!} - {!! $route->naar !!}</option>
#endforeach
</select>
</div>
</div>
#endif
EDIT
I've 2 dropdown menus. When one dropdown is selected the other one should receive a number from the database and show the right value for example bicycle. When the first dropdown menu is selected it post a request and receives the values back. When I receive information back for a text box I say:
$("#van").val(result.van);
But how do I have to do this with a dropdown menu?
<script>
$(document).ready(function () {
var xhr;
});
$("#standaardroute").change(function(e) {
csrf = $("#token").attr('content')
option = $(this).val();
$.ajax({
url: '/public/receiveuserinformation',
type: 'POST',
data: { option_id: option },
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', csrf);},
success: function(result) {
$("#van").val(result.van);
//here should be something for the dropdownmenu
}
});
});
</script>
Suppose you've two options in an array: $types = array('1' => 'car', '2' => 'bicycle'); and you're saving it in products table and you've current product data in $product variable
<select>
<?php foreach($types as $type_id => type_name): ?>
<option value="<?php echo $type_id; ?>" <?php if($type_id == $product->type) echo "selected"; ?>>
<?php echo $type_name; ?>
</option>
<?php endforeach; ?>
</select>
EDIT: if you're using blade in laravel then you could simply achieve it by doing this:
{!! Form::label('type', 'Type: ') !!}
{!! Form::select('type', $types !!}
EDIT2: Try this:
<option value="{!! $route->id !!}" {{ ($standaardroute->route == $route->id) ? 'selected':'' }}>{!! $route->van !!} - {!! $route->naar !!}</option>
Note: replace $standaardroute->route your actual variable
EDIT3: Put this inside your success function:
$('#van option').each(function(){
$(this).removeAttr('selected');
if($(this).val() == result.van){
$(this).attr('selected', 'selected');
}
});
Note: I've not tested this

Categories