【问题标题】:Delete a record from table using ajax in laravel 5在 laravel 5 中使用 ajax 从表中删除记录
【发布时间】:2015-08-22 10:51:16
【问题描述】:

我想使用 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"

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

我想删除被点击的产品。

谁能帮忙?

【问题讨论】:

  • delete 调用不需要任何参数。只需执行$product-&gt;delete();。另外,使用DELETE 作为ajax 方法,而不是POST
  • @StuartWagner 我也试过了。问题是,它会删除表格的第一行,而与单击的行无关
  • 如果您在控制器中的delete() 调用之前return $product;,并将console.log(msg); 添加到您的ajax 调用中,您会得到什么?
  • console.log(msg) 没有显示任何内容。
  • 您确定将 Ajax 请求发送到正确的路径吗?

标签: php ajax laravel laravel-5


【解决方案1】:

你的问题在这里:

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,所以你只需要通过事件来查询它。

【讨论】:

  • 我也试过了,先生。我想删除被点击的行,它工作正常,但只有第一行被删除,而与点击的行无关。
  • 那么解决办法是什么?我的意思是我需要做什么?
  • 解决方案是将您的查询更改为类似 $(e.target).attr('data-id').... 添加 "debugger;"在您的点击处理程序中,并在您的 javascript 控制台中检查它的正确性。
  • 我使用了$(this).attr('data-id'),它成功了!谢谢你:)
【解决方案2】:

我们必须发送请求如何 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;
});

更多参考请看这篇文章

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

【讨论】:

    【解决方案3】:

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

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

    到这里:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2017-02-19
        • 1970-01-01
        • 1970-01-01
        • 2019-04-12
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 2017-02-14
        • 2016-02-14
        相关资源
        最近更新 更多