Ajax 取错了产品 ID Laravel

Ajax takes wrong product id Laravel

我有一个 Laravel 测试项目,我正在尝试根据输入的数量值更新总成本。 这是我的 ajax:

$(document).ready(function() {
$('input[name=inputModal]').change(function() {
let qty = parseInt($('input[name=inputModal]').val());
let id = $('.card').data('id');
$.ajax({
url: '/modal/update/' + id,
dataType: 'JSON',
data:{
  qty:qty
},
success: function(response) {
$('.totalPrice').html(response.totalPrice);
}
});
return false;
});
});

我还试图进行隐藏输入并从中获取值。但尽管如此,当我更改输入值时,ajax 始终接受 ID 4,无论我选择哪个 ID。

费用更新路线:

Route::get('/modal/update/{id}', [BasketController::class, 'modal_order_update'])->name('modal_order_update');

购物车控制器:

public function modal_order_update(Request $request, $id){
    $product = Product::find($id);
    $modalQty = $request->qty;
      return response()->json([
            'price' => $product->price*$modalQty
       ]);
  }

模态 window:

<!-- 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="hidden" name="item_price"> -->
                                <input type="number" name="inputModal" min="1" max="100"></input>
                        </th>
                      </tr>
                      <tr>
                        <td colspan="3"><h5>Total cost:</h5></td>
                        <td class="d-flex"><h5 class="totalPrice"></h5><h5>AZN</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>

单个数字(2,3,4)是用户选择的产品的id。 例如:4? Qty = 2 - 用户更改产品数量。第一个数字是 id,出于某种原因它总是 4。

index.blade.php where modal included with @include directive:
@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" data-id="{{$item->id}}">Buy this item now</a>
              </div>
              </div>
            </div><!--end card-->
          @endforeach
       @endforeach
    </div>
</section>
@endsection

为了解决这个问题,我做了以下工作:

通过点击一个产品,我给了他当前的id。

$(document).ready(function() {
    $('.product-icon-container').find('.modal_order').click(function(event) {
        event.preventDefault();
        $.ajax({
            url: $(this).attr('href'),
            dataType: 'JSON',
            success: function(response) {
                $('.basket-prod-name').html(response.name);
                $('.modal_order').attr('data-id', response.modalProdId); //this line gives the current id
                $('.basketimg').attr('src', response.img);
                $('input[name=inputModal]').val(1);
                $('.totalPrice').html(response.price);
                $('#staticBackdrop').modal('show');
            }
        });
        return false;
    });
});

CartController 中的代码:

public
function modal_order($id) {
    $product = Product::find($id);
    return response() - > json([
        'modalProdId' => $product - > id, //this line gives the current id
        'name' => $product - > name,
        'img' => "/img/products/".$product - > cardImage - > path,
        'price' => $product - > price
    ]);
}

这里我就用之前获取到的id。然后我跟踪变化并计算最终成本:

$('input[name=inputModal]').change(function() {
    let qty = parseInt($('input[name=inputModal]').val());
    let id = $('.card').find('.modal_order').attr('data-id');
    $.ajax({
        url: '/modal/update/' + id,
        dataType: 'JSON',
        data: {
            qty: qty
        },
        success: function(response) {
            $('.totalPrice').html(response.price);
        }
    });
    return false;
});

购物车控制器:

public
function modal_order_update(Request $request, $id) {
    $product = Product::find($id);
    $modalQty = $request - > qty;
    return response() - > json([
        'price' => $product - > price * $modalQty
    ]);
}

这里是路线,如果有人需要的话:

Route::get('/modal/{id}', [CartController::class, 'modal_order'])->name('modal_order');

Route::get('/modal/update/{id}', [CartController::class, 'modal_order_update'])->name('modal_order_update');