Dynamic Dependent Drop down selection in Laravel - php

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.

Related

Laravel: Passing selected values to route function from dropdown selection

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

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');

How can i get value from select option using ajax and php

I have 2 select box option, city and district. I use ajax go get district name when I choose on the city. For this process I have succeed but when I click submit I get the error message Undefined index: district ,as this picture you can see
result image.
Here is my ajax code:
$(document).ready(function($) {
$("#city").change(function() {
var search_id = $(this).val();
$.ajax({
url: "search.php",
method: "post",
data: {search_id:search_id},
success: function(data){
$("#district").html(data);
}
})
});
});
Here is HTML code:
<form action="" method="post">
select city:
<select name="city" id="city">
<option value="1">Phnom Penh</option>
<option value="2">Kampong Soam</option>
<option value="3">Siem Reap</option>
</select>
select district:
<select name="distrcit" name="district" id="district">
<option>Select District</option>
</select>
<input type="submit" name="submit">
</form>
Here is PHP code:
<?php
if(isset($_POST['submit'])){
echo $_POST['city'];
echo $_POST['district'];
}
?>
//ajax request
<?php
if(isset($_POST['search_id'])){
$search_id = $database->escape_string($_POST['search_id']);
if(!empty($search_id)){
// $output = array();
$sql = "SELECT * FROM district WHERE ref_id = '$search_id'";
$districts = District::find_this_query($sql);
foreach($districts as $district){
// echo $district->id;
// echo $district->district_name;
$output .= "<option value='{$district->id}'>{$district->district_name}</option>";
}
echo $output;
}
}
?>
You have set name twice in select box. assign name only once:
so make it:
<select name="district" id="district">
<option>Select District</option>
</select>
I think this way is not very clean, you may create an ajax request returning values in json format and then append resultats in the select tag using
new Option(text, value);
please define name one time only :
<select name="district" id="district">
<option>Select District</option>
In the HTML you have declared name attributes 2 times:
<select name="distrcit" name="district" id="district">
Please replace with:
<select name="district" id="district">
<form action="" method="post">
select city:
<select name="city" id="city">
<option value="1">Phnom Penh</option>
<option value="2">Kampong Soam</option>
<option value="3">Siem Reap</option>
</select>
select district:
<select name="distrcit" name="district" id="district">
<option>Select District</option>
</select>
<input type="submit" name="submit">
</form>

PHP - MySQL : how to get item_id in the same page when i select the item_name in option dropdown

I need to show the item_id when I click one of the item_name list in the dropdown. And when I click submit, the item_name and item_id got by $_POST. Can javascript use to do that?
<?php
$brg="SELECT item_id, item_name FROM tblItem";
$b=mysql_query($brg);
?>
<td align="center">
<select name="item_name">
<?php while($br=mysql_fetch_array($b)){ ?>
<option value=<?echo $br[0].'_'.$br[1]?> selected>
<?php echo $br[1]; ?>
</option>
<?php } ?>
</select>
</td>
Jup, that's possible with Javascript.
Your HTML:
<select name="item_name">
<option value="1_Cheese">Cheese</option>
<option value="2_Cars">Cars</option>
<option value="3_Planes">Planes</option>
</select>
<input type="button" onclick="alert(getSelectedValue())" value="Get Select Id" />​
And your Javascript, to access the ID from the options value:
function getSelectedValue()
{
var sel = document.getElementsByName('item_name')[0];
return sel.options[sel.selectedIndex].value.split("_")[0];
}
See this fiddle: http://jsfiddle.net/acz6Q/
It would be a little easier with jQuery (also appended an event handler):
$(document).ready(function()
{
$("select[name=item_name]").on("change", function()
{
alert("new item id = " + $(this).val().split("_")[0]);
}); ​
});
And here is the jQuery version fiddle: http://jsfiddle.net/acz6Q/1/
Hope this helps!
Try this:
<form action="" method="post">
<input type="hidden" id="item_id" name="item_id" />
<input type="hidden" id="item_name" name="item_name" />
<select id="my_select" name="my_select">
<option value="item_id_1">item_name_1</option>
<option value="item_id_2">item_name_2</option>
<option value="item_id_3">item_name_3</option>
</select>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#my_select").change(function() {
$("#item_id").val($("#my_select").val());
$("#item_name").val($("#my_select option:selected").text());
});
});
</script>
Note that you need to include the jQuery library first. Also you can see how it works from here jsfiddle.net/2FsNP/3. And with this method you don't need to combine between value and text of the option tag with the underscore.

Categories