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 ?