Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a record from table using ajax in laravel 5

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 ?

like image 231
Saiyan Prince Avatar asked Oct 31 '22 02:10

Saiyan Prince


1 Answers

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.

like image 104
Rob_vH Avatar answered Nov 09 '22 06:11

Rob_vH