Маршрут вызова Ajax laravel не найден

Я хочу сделать подтверждение удаления laravel с помощью Modal, я вызываю маршрут laravel в ajax, но почему маршрут не найден.

это мой маршрут в laravel

Route::delete('delete-product/{productId}', 'StoreController@hapus')->name('product.delete');

это мое удаление ajax..

$(document).on('click', '.delete-modal', function() {
        $('.modal-title').text('Delete');
        $('#id_delete').val($(this).data('productId'));
        $('#deleteModal').modal('show');
        productId = $('#id_delete').val();
    });
    $('.modal-footer').on('click', '.hapus', function() {
        $.ajax({
            type: 'DELETE',
            url: 'delete-product/' + productId,
            data: {
                '_token': $('input[name=_token]').val(),
            },

когда я нажимаю значок корзины, модальное отображается, но в модальном, когда я нажимаю кнопку удаления, затем проверяю элемент в браузере, мой маршрут не найден

это элемент проверки

Request URL: http://localhost:8000/delete-product/
    Request Method: DELETE
    Status Code: 404 Not Found
    Remote Address: 127.0.0.1:8000
    Referrer Policy: no-referrer-when-downgrade

почему URL-адрес просто delete/product .... не включает идентификатор, хотя мой URL-адрес в ajax вызывается так

......
  url: 'delete-product/' + productId,
.....

это мой код лезвия

    @if(sizeof($resp->content) > 0)
    <ul class="the-product">
        @foreach($resp->content as $item)
            <li>
                @if(isset($store) && $store->storeId == $item->store->storeId)
                <a href="#" class="like"><i class="icofont-ui-love"></i></a>
                @else
                <a class="btn btn-danger delete-modal"><i class="fa fa-trash" data-id="{{$item->productId}}"></i></a>
                <a class="btn btn-danger" onclick="return myFunction();" href="{{url('edit.product', $item->productId)}}"><i class="icofont-ui-edit"></i></a>
                {{-- <a href="edit-product/{{$item->productId}}" class="icon-product"><i class="icofont-ui-edit"></i></a> --}}
                {{-- <a href="{{route('product.delete',$item->productId)}}" class="icon-product"><i class="icofont-ui-delete"></i></a> --}}
                @endif
                {{-- onclick="ajaxContent(event, this);" --}}
                <a href="productDetail/{{ $item->productId }}" class="the-item @if($item->discount > 0)on-promo @endif">

                    @if($item->discount > 0)
                        <div class="prod-rib">{{ $item->discount }}% Off</div>
                    @endif
                    <img data-src="@if($item->imageId != null){{ config('constant.showImage').$item->imageId }}@else{{ asset('images/no-image-available.png') }}@endif"
                        src="@if($item->imageId != null){{ config('constant.showImage').$item->imageId }}@else{{ asset('images/no-image-available.png') }}@endif"
                        alt="{{ $item->productNm }}">
                    <div class="prod-name">{{ $item->productNm }}</div>
                    <div class="prod-rev">
                        @for($i=0; $i<5;$i++)
                            @if($i<$item->reviewRate)
                            <img src="{{asset('img/kopi-on.svg')}}" />
                            @else
                            <img src="{{asset('img/kopi.svg')}}" />
                            @endif
                        @endfor
                        <span>{{ $item->reviewCount }} ulasan</span>
                    </div>
                    <div class="prod-price">
                            @if($item->discount > 0)
                            <span>Rp. {{ number_format($item->price,0,',','.') }}</span> Rp. <i>{{ APIHelper::discountPrice($item->discount, $item->price) }}</i>
                            @else
                            Rp. <i>{{ APIHelper::discountPrice($item->discount, $item->price) }}</i>
                            @endif
                    </div>
                </a>
                <a href="#" class="add-cart" onclick="addToCart({{ json_encode($item) }})">Add to cart <i class="icofont-cart"></i></a>
                {{-- //onclick="ajaxContent(event, this);" --}}
                <a href="{{url('/store-detail/'.$item->store->storeId)}}"  class="the-store">
                    <img src="@if($item->store->storePic != null){{ config('constant.showImage').$item->store->storePic }}@else{{ asset('images/no-image-available.png') }}@endif" />
                    {{ $item->store->storeNm }}
                    <span>{{ $item->store->percentFeedback }}% ({{ $item->store->totalFeedback }}
                            feedback)</span>
                </a>
            </li>
        @endforeach
    </ul>
    <ul class="pagination">
        <li class="disabled">
            <span><i class="icofont-rounded-double-left"></i></span>
        </li><li class="disabled">
            <span><i class="icofont-rounded-left"></i></span>
        </li>
        {{-- active --}}
        @for ($i = 0; $i < $resp->totalPages && $i < 5; $i++)

        <li class="" onclick="ajaxContent(event, this,null,{'key':'page','value':{{$i+1}} })">
            <span>{{$i + 1}}</span>
        </li>
        @endfor
        <li>
            <a href="#"><i class="icofont-rounded-right"></i></a>
        </li>
        <li>
            <a href="#"><i class="icofont-rounded-double-right"></i></a>
        </li>
    </ul>
@else
    <div class="container clearfix">
        <div class="style-msg errormsg mt-5">
            <div class="sb-msg"><i class="icon-remove"></i><strong>Maaf</strong>, pencarian anda tidak cocok dengan
                produk apapun. Silahkan coba lagi
            </div>
        </div>
    </div>
@endif

    <!-- Modal form to delete a form -->
    <div id="deleteModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    <h3 class="text-center">Are you sure you want to delete the following post?</h3>
                    <br />
                    <form class="form-horizontal" role="form">
                        <div class="form-group">
                            <label class="control-label col-sm-2" for="id">ID:</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="id_delete" disabled>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-2" for="title">Title:</label>
                            <div class="col-sm-10">
                                <input type="name" class="form-control" id="title_delete" disabled>
                            </div>
                        </div>
                    </form>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger hapus" data-dismiss="modal">
                            <span id="" class='glyphicon glyphicon-trash'></span> Delete
                        </button>
                        <button type="button" class="btn btn-warning" data-dismiss="modal">
                            <span class='glyphicon glyphicon-remove'></span> Close
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).on('click', '.delete-modal', function() {
            $('.modal-title').text('Delete');
            $('#id_delete').val($(this).data('productId'));
            $('#deleteModal').modal('show');
            productId = $('#id_delete').val();
        });
        $('.modal-footer').on('click', '.hapus', function() {
            $.ajax({
                type: 'DELETE',
                url: 'delete-product/{productId}',
                data: {
                    '_token': $('input[name=_token]').val(),
                },
                success: function(data) {
                    toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
                    $('.item' + data['id']).remove();
                    $('.col1').each(function (index) {
                        $(this).html(index+1);
                    });
                }
            });
        });
</script>

как написать URL в ajax? ПОМОГИТЕ плиз..


person Bian    schedule 17.02.2019    source источник
comment
Можешь поделиться кодом блейда?   -  person Md.Sukel Ali    schedule 17.02.2019
comment
были добавлены выше   -  person Bian    schedule 17.02.2019
comment
Вы вошли productId в консоль внутри функции, которая выполняет вызов ajax? Там показывает?   -  person unclexo    schedule 17.02.2019
comment
пожалуйста, попробуйте выполнить вручную ваш запрос ajax с этим, например. delete-product/3, чтобы проверить, работает ли он. если это удаление продукта с идентификатором 3, это означает, что что-то не так с вашим идентификатором продукта, который вы передаете в свой запрос ajax. если нет, то что-то еще не так. например маршруты   -  person daenerysTarg    schedule 17.02.2019


Ответы (1)


В вашем случае в следующем коде:

$(document).on('click', '.delete-modal', function() {
    $('.modal-title').text('Delete');
    $('#id_delete').val($(this).data('productId'));
    $('#deleteModal').modal('show');
    productId = $('#id_delete').val();
});

ProductId — это локальная переменная, имеющая область видимости функции. Вы не можете ссылаться на него снаружи, если вы не объявите его глобально вверху.

Когда вы попытаетесь сослаться на него позже, он не будет иметь никакого значения (undefined).

Во-вторых, вам нужно изменить

url: 'delete-product/{productId}'

с участием

url: '/delete-product/' + productId,

Итак, ниже приведен код:

jQuery(document).ready(function($){

    $(document).on('click', '.delete-modal', function() {
        $('.modal-title').text('Delete');
        $('#id_delete').val($(this).data('productId'));
        $('#deleteModal').modal('show');
    });

    $('.modal-footer').on('click', '.hapus', function() {

        var productId = $('#id_delete').val();
        $.ajax({
            type: 'DELETE',
            url: '/delete-product/' + productId,
            data: {
                '_token': $('input[name=_token]').val(),
            },
            success: function(data) {
                toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
                $('.item' + data['id']).remove();
                $('.col1').each(function (index) {
                    $(this).html(index+1);
                });
            }
        });
    });
});
person Mihir Bhende    schedule 17.02.2019