Sai*_*nce 5 php ajax laravel 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
Run Code Online (Sandbox Code Playgroud)
调节器
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']);
}
Run Code Online (Sandbox Code Playgroud)
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;
});
Run Code Online (Sandbox Code Playgroud)
**编辑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"
Run Code Online (Sandbox Code Playgroud)
问题是,这会删除产品,但只删除第一行而不是单击的那一行.
我想删除点击的产品.
有人可以帮忙吗?
你的问题在这里:
var dataId = $('#btnDeleteProduct').attr('data-id');
Run Code Online (Sandbox Code Playgroud)
你只会得到第一个,因为你在所有按钮上使用了重复的 id。所以 id sizzle 查询将为你得到第一个。
如果您在删除控制器中添加 dd($id) ,您将会看到这一点。它始终是第一个的 id。您可以通过相对于 event.target 查询来获取 data-id 属性。
您将需要使用调试器;回调中的语句来测试这一点,但查询应该类似于:
$(e.target).attr('data-id');
Run Code Online (Sandbox Code Playgroud)
或者
$(this).attr('data-id');
Run Code Online (Sandbox Code Playgroud)
事件目标应该是被单击的按钮,并且您在该按钮上设置了 data-id,因此您只需通过事件查询它即可。