【问题标题】:How To Pass Jquery Values / Variables To PHP In Laravel如何在 Laravel 中将 Jquery 值/变量传递给 PHP
【发布时间】:2018-03-08 01:22:14
【问题描述】:

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

Form and Seat Structure Image

我该如何解决这个问题?

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

【问题讨论】:

  • 如果你做一个控制台登录项目它会显示什么?我看到你用过 var()... 你的意思是 val() ?
  • 旁注;给定足够的数据,循环内的$.post 效率可能非常低。循环、收集数据并将单个POST 作为数组发送可能会更好。
  • @RăducanuIonuţ - 什么都没有。但是,当我使用 str.push(item);和警报(str.join(',')); ,它给了我选择的座位号。是的,它是 val()。
  • 您在使用post方式时没有提供token
  • @TimLewis - 我不知道。我该怎么做??

标签: php jquery database laravel


【解决方案1】:

为了提高效率,将$.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")&lt;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"
    }
});

【讨论】:

  • 当我使用这个 btnShowNew 函数时,它禁用了我的座位结构。我该如何解决这个问题??
  • “disabled my seat structure”是什么意思?
  • i.stack.imgur.com/E3nf8.png 这个结构。我想从此结构中将选定的座位号插入数据库。
  • 您只是无法点击它们吗?如果是这样,请检查您是否有任何控制台错误(在任何当前浏览器中按 F12,导航到 Console 选项卡)
  • 它给了我这个,加载资源失败:服务器响应状态为 404(未找到)-bootstrap-theme.min.css。我有 19 个错误。
【解决方案2】:

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

&lt;input type='hidden' name='seatNumbers' value='' id='seatNumbers'&gt;

on Laravel side : $request-&gt;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.

【讨论】:

    【解决方案3】:

    您可能想要更改此设置:

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

    至此:

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

    【讨论】:

    • 我可能是错的,但我认为你甚至不需要这里的.val()$(this).attr("title"); 应该自己工作。
    • attr() jQuery 函数在提供单个参数时返回一个字符串:指定属性名称的值。因此,在这种情况下,.val() 将应用于字符串并导致引发错误。顺便说一句,.val 仅与表单输入相关。
    • 嗨 Mohsin,如果您能描述一下为什么您的答案解决了作者问题,这将为以后找到此解决方案的人增加更多价值。
    猜你喜欢
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多