Update total cost based on input values ​using ajax (Laravel)

Viewed 715

I have a modal window where a user can buy a specific product. Before the forms, where you need to enter personal data, I display what the user has selected (product image, name, input (where the quantity changes) and the total amount:

CartController:

public function modal_order(Request $request, $id){
  $product = Product::find($id);
  return response()->json([
    'name' => $product->name,
    'img' => "/img/products/".$product->cardImage->path,
    'price' => $product->price*$request->qty."$",
  ]);
}

Ajax:

$(document).ready(function() {
  $('.product-icon-container').find('.modal_order').click(function (event){
    event.preventDefault();
    let qty = parseInt($('.inputModal').val());
    $.ajax({
      url: $(this).attr('href'),
      dataType: 'JSON',
      data:{
        qty:qty
      },
      success: function(response) {
        $('.basket-prod-name').html(response.name);
        $('.basketimg').attr('src', response.img);
        $('.totalPrice').html(response.price);
        $('#staticBackdrop').modal('show');
      }
    });
    return false;
  });

});

Input:

<input type="number" class="inputModal" name="" value="1" min="1" max="100">

If you set a standard value(quantity) in input, then everything is calculated fine, but when I change this value in the modal window, the amount does not change. It is clear that this is due to the fact that I get it using $request, but does anyone know how to do this asynchronously via ajax?

Modal bootstrap 4.5.3, which included via @include:

<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-body">
        <!-- -->
        <div class="login-form modal-purchase">
            <form action="" method="POST">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true" class="close-modal">&times;</span>
              </button>
              @csrf
                  <h2 class="text-center">Placing order</h2>
                  <table class="table">
                    <tbody>
                      <tr>
                        <th scope="row"><a href="/"><img class="basketimg mr-1" src=""></a></th>
                        <td><span class="basket-prod-name"></span></td>
                      </tr>
                      <tr>
                        <th scope="cols">
                                <input type="number" class="inputModal" min="1" max="100">
                        </th>
                      </tr>
                      <tr>
                        <td colspan="3"><h5>Total price:</h5></td>
                        <td><h5 class="totalPrice"></h5></td>
                    </tr>
                    </tbody>
                  </table>
                <div class="form-group">
                    <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="" placeholder="Enter your name" required autocomplete="name" autofocus>

                    @error('name')
                        <span class="invalid-feedback" role="alert">
                            <strong></strong>
                        </span>
                    @enderror

                </div>
                 <div class="form-group">
                      <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="" placeholder="E-Mail Address" required autocomplete="email">

                      @error('email')
                          <span class="invalid-feedback" role="alert">
                              <strong></strong>
                          </span>
                      @enderror

                 </div>
                 <div class="form-group">
                      <input id="phone" type="phone" class="form-control @error('phone') is-invalid @enderror" name="phone" placeholder="phone" required>

                      @error('password')
                          <span class="invalid-feedback" role="alert">
                              <strong></strong>
                          </span>
                      @enderror

                 </div>
                 <div class="form-group">
                    <button type="submit" class="btn btn-primary btn-lg btn-block">Place order</button>
                 </div>
            </form>
        </div>
        <!-- -->
      </div>
    </div>
  </div>
</div>

Index.blade.php where the modal is included:



@section('tittle', 'Main page')

@section('content')
@include(inc.flash)
@include(inc.modal-order)
<section class="container">
    <h1 class="s2tittle">Leaders of sells</h1>
      <div class="slider">
        @foreach($proditem as $product)
          @foreach($product->products as $item)
            <div class="card">
              <a href="/{{ $product->code }}/{{ $product->url }}/{{ $item->url }}"><img class="card-img-top" src="/img/products/{{ $item->cardImage->path}}" alt="Card image cap"></a>
              <div class="card-body">
                <a href="/{{ $product->code }}/{{ $product->url }}/{{ $item->url }}"><h5 class="card-title text-center">{{ $item->name }}</h5></a>
                <div class="prch"><span class="card-text">{{ $item->price }}</span><span class="card-text"><i class="{{ $item->is_available_icon }}"></i>{{ $item->is_available_text }}</span></div><br>
                <div class="prch second">
                <span><i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i></span>
                <span class="card-text feedback">10 reviews</span>
                </div>
              </div><!--end card-body-->
              <div class="card-footer"></div>
              <div class="text-center"><i class="fa fa-handshake"></i><span class="reg">Ordered by 10 people</span><br>
              <div class="product-icon-container" value="Display notification">
                <a href="{{ route('basket-add', [ 'id' => $item->id ]) }}" class="ajaxcartadd scrollOffset btn btn-success mt-2 mb-1">Add to cart</a>
                <a href="{{ route('modal-order', [ 'id' => $item->id ]) }}" class="modal_order btn btn-danger mt-2 mb-1">Buy this item now</a>
              </div>
              </div>
            </div><!--end card-->
          @endforeach
       @endforeach
    </div>
</section>
@endsection

The modal window opens by clicking the "buy this product now" button.

1 Answers

You can use item price which is shown inside your card div to calculate total price when value of qty gets changed.

First , whenever your buy now link is click get the .closest('.card') then using this find your item price span tag value and then set this value inside your modal in some hidden inputs.

Now, whenever quantity value gets change get that hidden input value , calculate total price and set new value inside total price .

Demo Code :

$('.product-icon-container').find('.modal_order').click(function(event) {
  event.preventDefault();
  //get item price
  var itm_price = $(this).closest(".card").find(".item_price").text()
  let qty = parseInt($('.inputModal').val());
  /* $.ajax({
     url: $(this).attr('href'),
     dataType: 'JSON',
     data: {
       qty: qty
     },
     success: function(response) {*/
  $('.basket-prod-name').html("soemthing");
  $('.basketimg').attr('src', "");
  $('.totalPrice').html(0);
  $('input[name=item_price]').val(itm_price) //set inside modal input-box
  $('.inputModal').val(0)
  $('#staticBackdrop').modal('show');
  /* }
    });
    return false;*/
});
//onchnage of qty
$(".inputModal").on("change", function() {
  //get item price
  var item_price = parseInt($('input[name=item_price]').val());
  console.log($('input[name=item_price]').val())
  var cal = ($(this).val()) * item_price;
  $(".totalPrice").text(cal) //set inside total price

})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="card">
  <a href="/{{ $product->code }}/{{ $product->url }}/{{ $item->url }}"><img class="card-img-top" src="/img/products/{{ $item->cardImage->path}}" alt="Card image cap"></a>
  <div class="card-body">
    <a href="/{{ $product->code }}/{{ $product->url }}/{{ $item->url }}">
      <h5 class="card-title text-center">something</h5>
    </a>
    <div class="prch">
      <!--add some class where price is there-->
      <span class="card-text item_price">12</span><span class="card-text"><i class="{{ $item->is_available_icon }}"></i>   ok ok </span></div><br>
    <div class="prch second">
      <span><i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i></span>
      <span class="card-text feedback">10 reviews</span>
    </div>
  </div>
  <!--end card-body-->
  <div class="card-footer"></div>
  <div class="text-center"><i class="fa fa-handshake"></i><span class="reg">Ordered by 10 people</span><br>
    <div class="product-icon-container" value="Display notification">
      <a href="{{ route('basket-add', [ 'id' => $item->id ]) }}" class="ajaxcartadd scrollOffset btn btn-success mt-2 mb-1">Add to cart</a>
      <a href="{{ route('modal-order', [ 'id' => $item->id ]) }}" class="modal_order btn btn-danger mt-2 mb-1">Buy this item now</a>
    </div>
  </div>
</div>
<div class="card">
  <a href="/{{ $product->code }}/{{ $product->url }}/{{ $item->url }}"><img class="card-img-top" src="/img/products/{{ $item->cardImage->path}}" alt="Card image cap"></a>
  <div class="card-body">
    <a href="/{{ $product->code }}/{{ $product->url }}/{{ $item->url }}">
      <h5 class="card-title text-center">something11</h5>
    </a>
    <div class="prch">
      <!--add some class where price is there-->
      <span class="card-text item_price">55</span><span class="card-text"><i class="{{ $item->is_available_icon }}"></i>   gud gud </span></div><br>
    <div class="prch second">
      <span><i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i></span>
      <span class="card-text feedback">10 reviews</span>
    </div>
  </div>
  <!--end card-body-->
  <div class="card-footer"></div>
  <div class="text-center"><i class="fa fa-handshake"></i><span class="reg">Ordered by 10 people</span><br>
    <div class="product-icon-container" value="Display notification">
      <a href="{{ route('basket-add', [ 'id' => $item->id ]) }}" class="ajaxcartadd scrollOffset btn btn-success mt-2 mb-1">Add to cart</a>
      <a href="{{ route('modal-order', [ 'id' => $item->id ]) }}" class="modal_order btn btn-danger mt-2 mb-1">Buy this item now</a>
    </div>
  </div>
</div>

<!--end card-->
<div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-body">
        <!-- -->
        <div class="login-form modal-purchase">
          <form action="" method="POST">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true" class="close-modal">&times;</span>
              </button> @csrf
            <h2 class="text-center">Placing order</h2>
            <table class="table">
              <tbody>
                <tr>
                  <th scope="row">
                    <a href="/"><img class="basketimg mr-1" src=""></a>
                  </th>
                  <td><span class="basket-prod-name"></span></td>
                </tr>
                <tr>
                  <th scope="cols">
                    <!--added this hidden field here-->
                    <input type="hidden" name="item_price">
                    <input type="number" class="inputModal" min="1" max="100">

                  </th>
                </tr>
                <tr>
                  <td colspan="3">
                    <h5>Total price:</h5>
                  </td>
                  <td>
                    <h5 class="totalPrice">10</h5>
                  </td>
                </tr>
              </tbody>
            </table>
            <div class="form-group">
              <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="" placeholder="Enter your name" required autocomplete="name" autofocus> @error('name')
              <span class="invalid-feedback" role="alert">
                            <strong></strong>
                        </span> @enderror

            </div>
            <div class="form-group">
              <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="" placeholder="E-Mail Address" required autocomplete="email"> @error('email')
              <span class="invalid-feedback" role="alert">
                              <strong></strong>
                          </span> @enderror

            </div>
            <div class="form-group">
              <input id="phone" type="phone" class="form-control @error('phone') is-invalid @enderror" name="phone" placeholder="phone" required> @error('password')
              <span class="invalid-feedback" role="alert">
                              <strong></strong>
                          </span> @enderror

            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary btn-lg btn-block">Place order</button>
            </div>
          </form>
        </div>
        <!-- -->
      </div>
    </div>
  </div>
</div>

Related