提交表单时更新会话变量。 AJAX。 Laravel

时间:2016-06-08 09:24:02

标签: javascript php jquery ajax laravel

我想要做的是当我提交带有票证代码的表单时,变量应该在没有页面刷新的情况下更新。我现在唯一实现的是提交表单而不刷新页面并且它有效。如果我提交表单然后手动刷新页面,变量会发生变化,但是我可以再次提交相同的表单。所以我想阻止它。这是我的表格:

Form

 <form id="ticket" action="prekiu-uzsakymas" method="get">
                        <input type="text" name="ticket">
                        <input id="btnSubmit" type="submit" value="Panaudoti kuponą">
                    </form>

这是我的AJAX

$(document).ready(function(){

            $('#ticket').on('submit',function(e){
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-Token': $('meta[name="csrf_token"]').attr('content')
                    }
                });
                e.preventDefault(e);


                $.ajax({

                    method:"GET",
                    url: $("#ticket").attr("action"),
                    data:$(this).serialize(),
                    dataType: 'html',
                    success: function(data) {
                        var statusHTML = '<h4><span class="label label-success">' +
                                '<i style="color: white" class="glyphicon glyphicon-ok"></i> Ticket used successfuly.</span></h4><br>';

                        $("#ticket").replaceWith(statusHTML);
                    },
                    error:function(data){
                        console.log("request failed");
                    }
                })

            });

        });

当我使用页面刷新提交表单时执行此操作:

foreach ($products as &$item) {
                    $item['price'] = $item['price'] - ($item['price'] * ($ticket->discount / 100));
                }

                Session::put('cart', $products);

一切正常但我不知道如何在没有页面刷新的情况下更新值,因此用户可以看到并且无法第二次提交表单。

1 个答案:

答案 0 :(得分:1)

将表单包装在会话变量中。

form

   @if ( !request()->session()->get('ticket') )
       <form id="ticket" action="prekiu-uzsakymas" method="POST">
           <input type="text" name="ticket">
           <input id="btnSubmit" type="submit" value="Panaudoti kuponą">
       </form>
   @else
        <h4>
            <span class="label label-success">
                <i style="color: white" class="glyphicon glyphicon-ok"></i> Ticket used successfully.
            </span>
        </h4>
        <br>
   @endif

如果会话中存储了折扣票,则可以防止显示该表单。

然后在您的代码中将其与购物车内容一起设置:

   // Check for ticket being sent in request, then check the session to make sure it's not set
   if ( request()->input('ticket') && (!request()->session()->get('ticket') ) ) {

       foreach ($products as &$item) {
           $item['price'] = $item['price'] - ($item['price'] * ($ticket->discount / 100));
       }

       Session::put('cart', $products);
       Session::put('ticket', request()->input('ticket'));
   }

   // Return your altered products in your response,
   // so you can update the info presented to the user
   return response()->json(['products' => $products]);

JavaScript/AJAX

   $(document).ready(function(){

       $.ajaxSetup({
           headers: {
               'X-CSRF-Token': $('meta[name="csrf_token"]').attr('content')
           }
       });

       $('#ticket').on('submit',function(e){

           e.preventDefault();

           $.ajax({

               method: $("#ticket").attr("method"),
               url: $("#ticket").attr("action"),
               data:$(this).serialize(),
               dataType: 'html',
               success: function(data) {
                   var statusHTML = '<h4><span class="label label-success">' +
                           '<i style="color: white" class="glyphicon glyphicon-ok"></i> Ticket used successfully.</span></h4><br>';

                   $("#ticket").replaceWith(statusHTML);

                   // data will now contain your products with updated prices
                   // You can access this with: data.products
                   // Example:
                   if (data.products) {
                       $(data.products).each( function(index) {
                           $("#product-"+$(this).id).find(".price").html($(this).price);
                       });
                   }
               },
               error: function(data){
                   console.log("request failed");
               }
           })

       });

   });

我还将form方法修改为POST,这是可选的。如果你使用它,你需要在routes.php中将此路由更改为Route::post。否则,您可以使用GET。