1

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.

5
  • U cant do it. With sessions at least. If u explain what do u need to me, i can suggest the right way to achieve it. Commented Jun 8, 2016 at 9:33
  • I want to update price that is shown without page refresh when form is submited. Commented Jun 8, 2016 at 9:36
  • Then u should update it like $('#price').text();. If u need to do it with array of products u need to create function, which will clear all data and repopulate it. Its much easier if u use things like AngularJs Commented Jun 8, 2016 at 9:45
  • Okay, is there are any alternative when form is submited do not let it submit again after page refresh ? Commented Jun 8, 2016 at 9:50
  • You need to use something like cookies or html 5 cache to save user action and add check it before form submit. Commented Jun 8, 2016 at 9:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for you effort! I'm getting this error now: prekiu-uzsakymas:263 Uncaught TypeError: Cannot read property 'each' of undefined in this line: dataType: 'html',
Hey mate! I did it with refresh! The thing that I needed most was the store used ticket in the session! Thanks!
Can u somehow invite me to chat ? I've one more question
I've added a check to see if "products" were returned in the response. I can't see the entirety of your project, so only you know what $products contains and what gets passed back through the AJAX response. You could also try using success: function(response) and then change if (data.products) to if (response.products).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.