【问题标题】:Update total cost based on input values ​using ajax (Laravel)使用 ajax (Laravel) 根据输入值更新总成本
【发布时间】:2021-04-08 11:40:45
【问题描述】:

我有一个模式窗口,用户可以在其中购买特定产品。在需要输入个人数据的表单之前,我会显示用户选择的内容(产品图片、名称、输入(数量变化的地方)和总金额:

购物车控制器:

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."$",
  ]);
}

阿贾克斯:

$(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 type="number" class="inputModal" name="" value="1" min="1" max="100">

如果你在输入中设置一个标准值(数量),那么一切都计算得很好,但是当我在模态窗口中更改这个值时,数量不会改变。很明显,这是因为我使用 $request 获取它,但是有人知道如何通过 ajax 异步执行此操作吗?

Modal bootstrap 4.5.3,通过@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:



@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

通过单击“立即购买此产品”按钮打开模式窗口。

【问题讨论】:

  • 打开浏览器网络选项卡并检查您的请求,如果一切正常,请检查响应。认为您在控制台中也遇到了一些错误,如果没有有关您的问题的更多信息,很难回答您的问题
  • 什么是.modal_order?请发布模态 HTML。
  • @Louys Patrice Bessette,已更新。
  • 抱歉,您能详细说明一下吗?当模态打开时,您正在进行 ajax 调用?当你设置你的数量值?
  • @Swati,当点击按钮时,会发出一个ajax 请求(在success 上的ajax 中可以看到调用模态$('# staticBackdrop').modal('show'); 的函数)。当来自服务器的响应时,设置总价的值。但我希望能够在打开的模式窗口中更改产品数量并异步计算总金额。

标签: jquery ajax laravel input


【解决方案1】:

qty 的值发生变化时,您可以使用显示在card div 中的商品价格来计算总价。

首先,每当您的buy now 链接被点击时,获取.closest('.card'),然后使用它找到您的item price 跨度标签值,然后在您的模态框内的一些隐藏输入中设置此值。

现在,每当数量值发生变化时,获取隐藏的输入值,计算总价并在total price 中设置新值。

演示代码

$('.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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-20
    • 2021-08-21
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2014-04-22
    • 1970-01-01
    相关资源
    最近更新 更多