簡體   English   中英

使用laravel 5中的ajax從表中刪除記錄

[英]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 **:

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

問題是,這會刪除產品,但只刪除第一行而不是單擊的那一行。

我想刪除點擊的產品。

有人可以幫忙嗎?

你的問題在這里:

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,因此您只需要通過事件查詢它。

我們必須發送請求如何以正常請求響應方式發送刪除數據請求。 需要改變一點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

正如@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....
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM