繁体   English   中英

如何在Laravel中将Jquery值/变量传递给PHP

[英]How To Pass Jquery Values / Variables To PHP In Laravel

我正在创建一个票务预订系统,我想将数据插入数据库。 像往常一样,我使用HTML表单,除座位号外,所有数据都存储到数据库中。 它并没有给我一个错误。 对于座位号,我使用了Jquery,我想将该Jquery值插入数据库中。 我不知道这是否可能。 (座位数=项目)

形式和座位结构图

我怎样才能解决这个问题?

这是我的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>

这是我的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');
}

这是我的路线。

Route::post('seatsinsert', [
    'uses' => 'SeatsController@seatsinsert',
    'as' => 'seatsinsert'
]);

为了提高效率,请将$.ajax移出循环,仅提交一次。 收集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"
        }
    });
});

编辑:由于$("#btnShowNows")<input type="submit" ...您需要在按下时防止提交:

$('#btnShowNew').click(function (e) {
    e.preventDefault();
    ...

实际处理AJAX提交。 还要注意我如何将_token值添加到要提交的data中; 应该避免任何CSRF_TOKEN异常。

您还必须调整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();
}

尽管由此引起了关于变量命名的另一条注释; 对于Seats模型的实例, $user不是一个好的变量名。

此外,模型是由传统单一( Seat ,没有Seats ),而它们所连接到数据库是复数( tbl_seatsseats等)

同样, $date$st在此处为null ,因为它们不会在$.ajax请求的data部分中提交。 为了解决这个问题,我们将添加:

data: {
    _token: "{{ csrf_field() }}",
    items: items,
    date: $('input[name=date]').val(),
    st: $('select[name=st]').val()
}

除非明确包含在AJAX请求中,否则不会提交FORM元素,因为永远不会物理提交表单(通过form.submit()或其他方式)。 可以将AJAX视为表单的副本,并且无需实际提交即可提交所有元素。

最后(我希望) return redirect('Seats'); 对于AJAX请求不执行任何操作。 您应该使用:

return response()->json(["message" => "Success"], 200); // Customize as needed

并通过$.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"
    }
});

将所有表格都保留在一个表格中不是更好..添加一个隐藏的输入字段(或任何其他类型)..在值中记录座位号并从那里提取数据。

<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.

您可能要更改此设置:

var item = $(this).attr('title').var();

对此:

var item = $(this).attr('title').val();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM