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');
Related
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.
Am working on a Laravel application whereby am capturing some input
fields consisting of dropdown fields on some cards whereby I submit them to the backend via AJAX.
On the backend I want to create a validation logic whereby there
should be only one husband or wife from the select dropdown
inputs captured on the frontend. This means the user should only select only one husband or wife from the select dropdown on the cards on the frontend
Form template
<form method="POST" action="#" id="phase3" accept-charset="UTF-8">
<!-- CSRF TOKEN-->
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
<!-- Card 1-->
<div class="col-md-4 col-sm-12 phonecard3">
<div class="innerDiv">
<!-- Gender -->
<div class="row">
<label class="fm-input"> Relation :</label>
<select class="fm-input otherMenu" id="relation1" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
</div>
</div>
<!-- End card 1-->
<!-- Card 2-->
<div class="col-md-4 col-sm-12 phonecard3">
<div class="innerDiv">
<!-- Gender -->
<div class="row">
<label class="fm-input"> Relation :</label>
<select class="fm-input otherMenu" id="relation2" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
</div>
</div>
<!-- End card 2-->
<!-- Card 3-->
<div class="col-md-4 col-sm-12 phonecard3">
<div class="innerDiv">
<!-- Gender -->
<div class="row">
<label class="fm-input"> Relation :</label>
<select class="fm-input otherMenu" id="relation3" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
</div>
</div>
<!-- End card 3-->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<button class="btn btn-lg lov1" type="submit"> Save & Create for Spouse & Children <i class="fa fa-check-circle" ></i></button>
</div>
</div>
</form>
AJAX code to submit form details
$("#phase3").submit(function( event ) {
event.preventDefault();
//Fetch data
var token = $('#token').val();
var relation1 = $("#relation1").val();
var relation2 = $("#relation2").val();
var relation3 = $("#relation3").val();
//Store in a JS object
var type ={
'token': token,
//Relations
'relation1' : relation1,
'relation2' : relation2,
'relation3' : relation3
};
//console.log(type);
$.ajax({
type: "POST",
url: "submitPhase3",
data:JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function(response){
//console.log(response);
},
//Alert errors from backend
error: function(data) {
//console.log(data);
}
});
});
Backend PHP function to handle request
public function submitPhase3(Request $request){
dd($request->all());
$validation = $this->validate($request, [
//Relations
'relation1'=> isset($request->relation1) ? $request->relation1 : null,
'relation2'=> isset($request->relation2) ? $request->relation2 : null,
'relation3'=> isset($request->relation3) ? $request->relation3 : null,
]
);
}
Custom validator in App/Providers/AppServiceProvider.php file
public function boot(){
//Custom Validation
Validator::extend('relation',
function ($attribute, $value, $parameters, $validator){
$relationMaxMap = [];//create a map with key=>'value', value=>'maximum'
$relations = Config::get('app.relations');
foreach($relations as $relation) {
$relationMaxMap[$relation['value']] = $relation['maximum'];
}
//$relationMaxMap will be [1=>1, 2=>1,3=>10,4=>10];
$requestMap = []; //map from the request 'value'=>'count', this way you know what relations has been selected and how many times
foreach($values as $value) {
if(!isset($values[$value])) { //at the begining
$requestMap[$value] = 1;
}
$requestMap[$value]++;
}
//Compare the maps to check if it execedes the maximum allowed in your app
foreach($relationMaxMap as $value=>$maximum) {
if($requestMap[$value] > $maximum) {
return false;
}
}
return true;
});
}
New Function
public function submitPhase3(Request $request){
dd($request->all());
$validation = $this->validate($request, [
//Pull code from custom validator
'relation' => 'relation'
]
);
}
I would define a list of values in a config and pass them to the given view (key being the value and the text being what is displayed):
$relations=[
['value'=>1,'display'=>'Wife','maximum'=>1]
['value'=>2,'display'=>'Husband','maximum'=>1],
['value'=>3,'display'=>'Son','maximum'=>10],
['value'=>4,'display'=>'Daughter','maximum'=>10]
];
Controller:
[...]
return view('my_view', Config::get('app.relations');
[...]
View:
[...]
#foreach ($relations as $relation)
<option value="{{$relation['value']}}">{{$relation['display']}}</option>
#endforeach
[...]
I would also pass the relations as an array in a custom validator:
<?php
class CustomValidator extends \Illuminate\Validation\Validator
{
public function validateRelations($attribute, $values, $parameters)
{
$relationMaxMap = [];//create a map with key=>'value', value=>'maximum'
$relations = Config::get('app.relations');
foreach($relations as $relation) {
$relationMaxMap[$relation['value']] = $relation['maximum'];
}
//$relationMaxMap will be [1=>1, 2=>1,3=>10,4=>10];
$requestMap = []; //map from the request 'value'=>'count', this way you know what relations has been selected and how many times
foreach($values as $value) {
if(!isset($values[$value])) { //at the begining
$requestMap[$value] = 1;
}
$requestMap[$value]++;
}
//Compare the maps to check if it execedes the maximum allowed in your app
foreach($relationMaxMap as $value=>$maximum) {
if($requestMap[$value] > $maximum) {
return false;
}
}
return true;
}
}
NOTE: Code not tested, but this is how I would approach this
Also I would use the validator is a form request
I think I will use this method, hoping to help you
$options = ['Husband', 'Wife', 'Son', 'Daughter']; // rule default
$relation1 = $request->input('relation1'); // value of relation 1
$relation2 = $request->input('relation2') // value of relation 2
// get rule of relation 2, if relation 1 choose husband
//then relation2 will remove husband --> ['Wife', 'Son', 'Daughter']
$ruleForRelation2 = array_diff($options, [$relation1]);
// same relation 1
$ruleForRelation3 = array_diff($options, [$ruleForRelation2]);
$validation = $this->validate($request, [
'relation1'=> Rule::in($options),
'relation2'=> Rule::in($ruleForRelation2),
'relation3'=> Rule::in($ruleForRelation3),
]
);
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>
I have a view show.php of my single product, when user click on ADD PRODUCT my controller CartController.php update my session cart and update my cartSession table,
Now i'm tryng to put new data (Color input,Size input, Quantity input) on my session and also in my CartSession table. But i dont know why it doesn't work.
-I think that the principal problem is that $request->get('input') doesn't pass to my CartController.php , i tried to return
$request->all() and there is not nothing.
CartController.php
namespace dixard\Http\Controllers;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Product;
use dixard\CartSession;
use dixard\CartItem;
use dixard\Shipping;
use Session;
// i think that all classes are ok
public function add(Product $product, CartSession $CartSession,Request $request)
{
$id = $request->get('id');
$cart = \Session::get('cart');
$product->quantity = $request->get('qty');
$product->size = $request->get('size');
$product->color = $request->get('color');
$cart[$product->id] = $product;
\Session::put('cart', $cart);
return $request->all(); // here i tried to get all inputs but it shows me nothing result
$subtotal = 0;
foreach($cart as $producto){
$subtotal += $producto->quantity * $producto->price;
}
$session_code = Session::getId();
$CartSession = new CartSession();
$session_exist = CartSession::where('session_code', $session_code)->orderBy('id', 'desc')->first();
if (isset($session_exist)) {
$s = new CartSession;
$data = array(
'subtotal' => $subtotal,
);
$s->where('session_code', '=', $session_code)->update($data);
}else {
$CartSession = new CartSession();
$CartSession->session_code = $session_code;
$CartSession->subtotal = $subtotal;
$CartSession->save();
}
//return $cart;
//salveremo tutte le informazioni nel array cart nella posizione slug
foreach($cart as $producto){
$this->saveCartItem($producto, $CartSession->id, $session_code, $cart);
}
return redirect()->route('cart-show');
}
Routes.php
Route::bind('product', function($id) {
return dixard\Product::where('id', $id)->first();
});
Route::get('cart/add/{product}', [
'as' => 'cart-add',
'uses' => 'CartController#add'
]);
show.php view
Get Data about the product is ok, title, description, color avaible, price ecc. all information pass to my view.
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="id" value="{{$product->id}}">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="p_color">Colore</label>
<select name="color" id="p_size" class="form-control">
#foreach($colors as $color)
<option value="{{ $color->color }}">{{ $color->color }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="size">Size</label>
<select name="size" id="p_size" class="form-control">
<option value="XS">XS</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="qty">Quantity</label>
<select name="qty" id="p_qty" class="form-control">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
</select>
</div>
</div>
</div>
<div class="product-list-actions">
<span class="product-price">
<span class="amount">{{$product->price}}</span>
<input type="submit" class="btn btn-lg btn-primary" >
ADD PRODUCT
</input>
</div><!-- /.product-list-actions -->
{!! Form::close() !!}
Thank you for your help!
You have to explicitly set the post-method to be "get" or you need to change your router to accept the request as post. Even though you're calling the route by name, Form::open defaults to "POST"
https://laravelcollective.com/docs/5.2/html#opening-a-form
Option 1. Change
Route::get('cart/add/{product}',...
to
Route::post('cart/add/{product}',...
Option 2. Change
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
to
{!! Form::open(['method'=>'GET', 'route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
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