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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30701229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:43:54  来源:igfitidea点击:

Delete a record from table using ajax in laravel 5

phpajaxlaravellaravel-5

提问by Saiyan Prince

I want to delete the record using ajax.

我想使用ajax删除记录。

view

看法

@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

controller

控制器

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 delete

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;
});

** Edit 1 **:

** 编辑 1 **:

Here's what I get if I just return console.log(msg)

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

The thing is that, this deletes the product, but only the first row and not the one that is clicked.

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

I want to delete the product which is clicked.

我想删除被点击的产品。

Can anyone help ?

任何人都可以帮忙吗?

采纳答案by Rob_vH

Your problem is here:

你的问题在这里:

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

You are only going to get the first one, because you are using a duplicate id on all buttons.. So an id sizzle query will get you the first one.

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

You will see this if you dd($id) in your delete controller. It's always the id of the first. You can get the data-id attribute by querying relative to event.target.

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

You will want to use the debugger; statement inside your call back to test this, but the query should be something like:

你会想要使用调试器;回调中的语句来测试这个,但查询应该是这样的:

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

or

或者

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

The event target should be the button that was clicked, and you set the data-id on that button, so you just need to query it via the event.

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

回答by Stuart Wagner

As @Rob_vH mentioned, your problem is with how you're getting the ID in your JavaScript. Try changing this:

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

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

to this:

对此:

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

回答by Priyank

try This,replace your this div,

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

with,

和,

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

now made javascript function named as,

现在将 javascript 函数命名为,

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

回答by umefarooq

We have to send request how laravel sending request for delete data in normal request response way. need to change little html

我们必须以正常的请求响应方式发送请求,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;
});

for more reference see this post

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

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

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