使用laravel 5中的ajax从表中删除记录

时间:2015-06-08 04:24:32

标签: php ajax laravel 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 **:

如果我只是返回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"

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

我想删除点击的产品。

有人可以帮忙吗?

4 个答案:

答案 0 :(得分:2)

你的问题在这里:

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

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

如果你删除控制器中的dd($ id),你会看到这个。它始终是第一个的身份。您可以通过查询相对于event.target来获取data-id属性。

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

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

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

事件目标应该是单击的按钮,并且您在该按钮上设置了data-id,因此您只需要通过事件查询它。

答案 1 :(得分:0)

我们必须发送请求如何以正常请求响应方式发送删除数据请求。需要改变一点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;
});

有关更多参考,请参阅此帖子

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

答案 2 :(得分:0)

正如@Rob_vH所提到的,您的问题在于如何在JavaScript中获取ID。尝试更改此内容:

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

到此:

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

答案 3 :(得分:0)

试试这个,替换你的这个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....
}