Delete a record from table using ajax in laravel 5

2019-02-17 22:17发布

问题:

I want to delete the record using 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

$('.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 **:

Here's what I get if I just 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"

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 ?

回答1:

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.

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.

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.



回答2:

We have to send request how laravel sending request for delete data in normal request response way. need to change little 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



回答3:

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

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

to this:

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


回答4:

try This,replace your this 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,

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