Update session variable when form is submited. AJAX. Laravel

What I want to do is when I submit my form with ticket code the variables should update without page refresh. What I only achieve now is submit form without page refresh and it works. And if I submit form and then refresh page manually the variables change, but then again I can submit the same form. So I want to prevent that. This is my form:

Form

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

This is my 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");
                    }
                })

            });

        });

This is what executes when I submit form with page refresh:

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

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

It all works but I don't know how to update values without page refresh so the user can see and cannot submit the form second time.

Upvotes: 1

Views: 2814

Answers (1)

Justin Origin Broadband
Justin Origin Broadband

Reputation: 1530

Wrap your form in a session variable check.

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

This prevents the form from being displayed if a discount ticket has been stored in the session.

Then set this in your code along with the cart contents:

   // 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]);

In your 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");
               }
           })

       });

   });

I've also modified the form method to be POST, which is optional. If you go with this, you need to change the route for this in your routes.php to be Route::post. Otherwise, you can use GET.

Upvotes: 1

Related Questions