Tôi muốn xóa bản ghi bằng ajax.Xóa bản ghi khỏi bảng bằng ajax trong laravel 5
xem
@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' => ['[email protected]', $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
khiển
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 xóa
$('.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;
});
** Sửa 1 **:
Dưới đây là những gì tôi nhận được nếu tôi chỉ trả lại 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"
Cái này là, điều này xóa sản phẩm, nhưng chỉ hàng đầu tiên và không phải là một trong đó là nhấp vào.
Tôi muốn xóa sản phẩm được nhấp.
Có ai giúp được không?
Bạn không cần bất kỳ tham số nào cho lệnh gọi 'delete'. Chỉ cần làm '$ product-> delete();'. Ngoài ra, sử dụng 'DELETE' làm phương thức ajax, không phải' POST'. –
@StuartWagner Tôi cũng đã thử điều đó. Vấn đề là, nó xóa hàng đầu tiên của bảng, bất kể hàng được nhấp vào –
Nếu bạn 'trả về $ product;' trước lệnh 'delete()' trong bộ điều khiển và thêm 'console.log (msg); 'để gọi ajax của bạn, bạn sẽ nhận được gì? –