使用 laravel 5 中的 ajax 从 table 中删除一条记录

Delete a record from table using ajax in laravel 5

我想删除使用 ajax 的记录。

查看

@foreach( $products as $product )
    <tr>
        <td>{{ $product->code }}</td>
        <td>{{ $product->name }}</td>
        <td>{{ $product->display }}</td>
        <?php $time = date('d M, Y h:i:s A', strtotime($product->created_at)); ?>
        <td>{{ $time }}</td>
        <td>
            <a href="{{ url('/admin/products/' . $product->id . '/edit') }}" class="links-dark edits pull-left">
                <i class="fa fa-edit fa-lg"></i>
            </a>
            <div id="deleteTheProduct">
                {!! Form::open(['method' => 'DELETE', 'id' => 'formDeleteProduct', 'action' => ['AdminProductsController@destroy', $product->id]]) !!}
                    {!! Form::button( '<i class="fa fa-trash fa-lg"></i>', ['type' => 'submit', 'class' => 'delete text-danger deleteProduct','id' => 'btnDeleteProduct', 'data-id' => $product->id ] ) !!}
               {!! Form::close() !!}
           </div>
       </td>
   </tr>
@endforeach

控制器

public function destroy( $id, Request $request ) {
    $product = Product::findOrFail( $id );

    if ( $request->ajax() ) {
        $product->delete( $request->all() );

        return response(['msg' => 'Product deleted', 'status' => 'success']);
    }
    return response(['msg' => 'Failed deleting the product', 'status' => 'failed']);
}

ajax删除

$('.deleteProduct').on('click', function(e) {
    var inputData = $('#formDeleteProduct').serialize();

    var dataId = $('#btnDeleteProduct').attr('data-id');

    $.ajax({
        url: '{{ url('/admin/products') }}' + '/' + dataId,
        type: 'POST',
        data: inputData,
        success: function( msg ) {
            if ( msg.status === 'success' ) {
                toastr.success( msg.msg );
                setInterval(function() {
                    window.location.reload();
                }, 5900);
            }
        },
        error: function( data ) {
            if ( data.status === 422 ) {
                toastr.error('Cannot delete the category');
            }
        }
    });

    return false;
});

** 编辑 1 **:

如果我只是 return console.log(msg)

,这就是我得到的结果
Object {
    id: "1",
    code: "PROD-521420",
    name: "Testing the product name",
    category_id: "3",
    short_description: "This is the short description"…
}
category_id: "3"
code: "PROD-521420"
created_at: "2015-06-07 23:00:31"
deleted_at: null
description: "This is the long description"
discount_price: "125.00"
display: "Enabled"
id: "1"
meta_description: "This is the meta description"
meta_keywords: "This is the meta keywords"
meta_title: "This is the meta title"
name: "Testing the product name"
price: "150.00"
short_description: "This is the short description"
updated_at: "2015-06-08 10:04:26"

问题是,这会删除产品,但只会删除第一行,而不是被点击的行。

我要删除被点击的商品

有人能帮忙吗?

我们必须如何发送请求 laravel 以正常的请求响应方式发送删除数据的请求。需要稍作改动 html

<button type="button" class="deleteProduct" data-token="{{ csrf_token() }}">Confirm</button>

$('.deleteProduct').on('click', function(e) {
    var inputData = $('#formDeleteProduct').serialize()+"&_method=delete&_token="+$(this).data(token);

    var dataId = $('#btnDeleteProduct').attr('data-id');

    $.ajax({
        url: '{{ url('/admin/products') }}' + '/' + dataId,
        type: 'POST',
        data: inputData,
        success: function( msg ) {
            if ( msg.status === 'success' ) {
                toastr.success( msg.msg );
                setInterval(function() {
                    window.location.reload();
                }, 5900);
            }
        },
        error: function( data ) {
            if ( data.status === 422 ) {
                toastr.error('Cannot delete the category');
            }
        }
    });

    return false;
});

有关更多参考,请参阅此 post

http://laravel.io/forum/02-20-2014-sending-a-delete-request-via-ajax

你的问题在这里:

var dataId = $('#btnDeleteProduct').attr('data-id');

您只会得到第一个,因为您在所有按钮上使用了重复的 ID。所以 id sizzle 查询将为您得到第一个。

如果你在你的删除控制器中使用 dd($id) 你会看到这个。它始终是第一个的 id。相对于event.target.

查询即可获取data-id属性

您将需要使用调试器;在你的回调中声明来测试这个,但查询应该是这样的:

$(e.target).attr('data-id');

$(this).attr('data-id');

事件目标应该是被点击的按钮,你在那个按钮上设置了data-id,所以你只需要通过事件来查询它。

如@Rob_vH 所述,您的问题在于如何在 JavaScript 中获取 ID。尝试改变这个:

var dataId = $('#btnDeleteProduct').attr('data-id');

对此:

var dataId = $(this).attr('data-id');

试试这个,替换你的这个 div,

<div id="deleteTheProduct">
                {!! Form::open(['method' => 'DELETE', 'id' => 'formDeleteProduct', 'action' => ['AdminProductsController@destroy', $product->id]]) !!}
                    {!! Form::button( '<i class="fa fa-trash fa-lg"></i>', ['type' => 'submit', 'class' => 'delete text-danger deleteProduct','id' => 'btnDeleteProduct', 'data-id' => $product->id ] ) !!}
               {!! Form::close() !!}
</div>

<input type='button' Value='Delete' onclick='deleteProduct($(this))' product_id='{!!$product->id!!}'/>

现在 javascript 函数命名为,

function deleteProduct(ele){
var product_id = ele.attr('product_id');
//Your Delete Product Ajax Code....
}