[英]How To Pass Jquery Values / Variables To PHP In Laravel
I am creating a Ticket Reservation System and I want to insert data into the Database. 我正在创建一个票务预订系统,我想将数据插入数据库。 As usual, I used HTML form and all the data goes to the database except seat numbers.
像往常一样,我使用HTML表单,除座位号外,所有数据都存储到数据库中。 And it doesn't give me an error.
它并没有给我一个错误。 For the seat numbers, I used Jquery and I want to insert that Jquery values into the database.
对于座位号,我使用了Jquery,我想将该Jquery值插入数据库中。 I don't know is this possible or not.
我不知道这是否可能。 ( Seat numbers = items )
(座位数=项目)
Form and Seat Structure Image 形式和座位结构图
How can I Fix this? 我怎样才能解决这个问题?
Here is my Seat.blade.php
这是我的
Seat.blade.php
#holder{
height:300px;
width:800px;
background-color:#F5F5F5;
border:1px solid #A4A4A4;
}
#place {
position:relative;
margin-top:33px;
margin-left:35px;
}
#place a{
font-size:80%;
}
#place li
{
list-style: none outside none;
position: absolute;
}
#place li:hover
{
background-color:yellow;
}
#place .seat{
background:url("img/Other/Available Seat.png") no-repeat scroll 0 0 transparent;
height:30px;
width:45px;
display:block;
}
#place .selectedSeat
{
background-image:url("img/Other/Disabled Seat.png");
}
#place .selectingSeat
{
background-image:url("img/Other/Booked Seat.png");
}
#place .row-3, #place .row-4{
margin-top:10px;
}
#seatDescription li{
verticle-align:middle;
list-style: none outside none;
padding-left:35px;
height:35px;
float:left;
font-family: Times New Roman;
font-size:120%;
color:#353c47;
}
</style>
<form class="form-horizontal" id="form1" method="POST" action="{{ route('seatsinsert') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="dt"> <br>
@if(session()->has('Msg'))
<h4 class="alert alert-success"> {{ session()->get('Msg') }} </h4>
@endif
<div class="form-group row">
<label for="example-date-input" class="col-2 col-form-label">Select Date :</label>
<div class="col-10">
<input class="form-control" type="date" name="date" placeholder="mm-dd-yyyy" id="example-date-input">
</div>
</div>
<div class="form-group">
<label for="exampleSelect1">Select Time :</label>
<select name="st" class="form-control" id="exampleSelect1">
<option>10.30 am</option>
<option>1.30 pm</option>
<option>4.30 pm</option>
<option>7.30 pm</option>
</select>
</div>
</div>
<h2 style="font-size:1.2em;font-family: Times New Roman;"> Choose seats by clicking below seats :</h2>
<div id="holder">
<ul id="place">
</ul>
</div>
<input type="submit" class="btn btn-primary" id="btnShowNew" value="Continue"> <br><br>
<script type="text/javascript">
$(function () {
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
var item = $(this).attr('title').val();
//str.push(item);
$.ajax({
type: "post",
url: "{{ route('seatsinsert') }}",
data: {items: item}
})
});
//alert(str.join(','));
})
});
</script>
</form>
Here is my SeatController.php
这是我的
SeatController.php
public function seatsinsert(Request $request) {
$date = $request->input('date');
$st = $request->input('st');
$item = $request->input('items');
//$item = item;
$user = new Seats();
$user->date = $date;
$user->st = $st;
$user->item = $item;
$this->validate($request, [
'date' => 'required'
]);
$user->save();
$request->session()->flash('Msg', 'Successfully Inserted !!');
return redirect('Seats');
}
Here are my Routes. 这是我的路线。
Route::post('seatsinsert', [
'uses' => 'SeatsController@seatsinsert',
'as' => 'seatsinsert'
]);
For efficiency's sake, move the $.ajax
outside of the loop and only submit once. 为了提高效率,请将
$.ajax
移出循环,仅提交一次。 Collect items
as an array of item
values, then POST
a single time. 收集
items
作为数组item
的值,则POST
一个单一的时间。
$('#btnShowNew').click(function (e) {
e.preventDefault();
var items = [];
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
items.push($(this).attr('title'));
});
$.ajax({
type: "post",
url: "{{ route('seatsinsert') }}",
data: {
_token: "{{ csrf_token() }}",
items: items,
date: $('input[name=date]').val(),
st: $('select[name=st]').val()
}, success: function(data){
console.log(data.message); // "Success"
}
});
});
EDIT: Since $("#btnShowNows")
is an <input type="submit" ...
you need to prevent the submit when being pressed: 编辑:由于
$("#btnShowNows")
是<input type="submit" ...
您需要在按下时防止提交:
$('#btnShowNew').click(function (e) {
e.preventDefault();
...
To actually handle the AJAX submission. 实际处理AJAX提交。 Also note how I added the
_token
value to your data
being submitted; 还要注意我如何将
_token
值添加到要提交的data
中; should avoid any CSRF_TOKEN
exceptions. 应该避免任何
CSRF_TOKEN
异常。
You'll have to adjust your PHP to handle items
as an array too, but that's pretty easy: 您还必须调整PHP以将
items
也处理为数组,但这很简单:
$this->validate($request, [
'date' => 'required'
]);
foreach($request->input("items") AS $item){
$user = new Seats();
$user->date = $date;
$user->st = $st;
$user->item = $item;
$user->save();
}
Although another side note on variable naming arises from this; 尽管由此引起了关于变量命名的另一条注释;
$user
is not a good variable name for an instance of a Seats
model. 对于
Seats
模型的实例, $user
不是一个好的变量名。
Also, models are by tradition singular ( Seat
, not Seats
) while the database they are attached to is plural ( tbl_seats
, seats
, etc) 此外,模型是由传统单一(
Seat
,没有Seats
),而它们所连接到数据库是复数( tbl_seats
, seats
等)
Also also, $date
and $st
would be null
here, since they aren't being submitted in the data
section of your $.ajax
request. 同样,
$date
和$st
在此处为null
,因为它们不会在$.ajax
请求的data
部分中提交。 To fix this, we would add: 为了解决这个问题,我们将添加:
data: {
_token: "{{ csrf_field() }}",
items: items,
date: $('input[name=date]').val(),
st: $('select[name=st]').val()
}
Unless explicitly included in an AJAX request, FORM
elements will not be submitted, as the form is never physically submitted (via form.submit()
or otherwise). 除非明确包含在AJAX请求中,否则不会提交
FORM
元素,因为永远不会物理提交表单(通过form.submit()
或其他方式)。 Think of AJAX as a copy of a form and all of it's elements being submitted without actually submitting it. 可以将AJAX视为表单的副本,并且无需实际提交即可提交所有元素。
Lastly (I hope) return redirect('Seats');
最后(我希望)
return redirect('Seats');
does nothing for an AJAX request. 对于AJAX请求不执行任何操作。 You should use:
您应该使用:
return response()->json(["message" => "Success"], 200); // Customize as needed
And handle via the success
function in your $.ajax
request: 并通过
$.ajax
请求中的success
函数进行处理:
$.ajax({
type: "post",
url: "{{ route('seatsinsert') }}",
data: {
_token: "{{ csrf_field() }}",
items: items,
date: $('input[name=date]').val(),
st: $('select[name=st]').val()
}, success: function(data){
console.log(data.message); // "Success"
}
});
Isn't it better to keep all the form in 1 piece .. add a hidden input field (or any other type) .. record the seat number/s in the value and pull that data from there. 将所有表格都保留在一个表格中不是更好..添加一个隐藏的输入字段(或任何其他类型)..在值中记录座位号并从那里提取数据。
<input type='hidden' name='seatNumbers' value='' id='seatNumbers'>
on Laravel side : $request->input('seatNumbers')
on the JS side : object.getElementById('seatNumbers').value
// you need to use this because .val() is not
updating the value in html but adding another node.
You might want to change this: 您可能要更改此设置:
var item = $(this).attr('title').var();
To this: 对此:
var item = $(this).attr('title').val();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.