Desidero eliminare il record utilizzando ajax.Eliminare un record dalla tabella utilizzando ajax in laravel 5
vista
@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
regolatore
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 eliminare
$('.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 **:
Ecco cosa ottengo se ho appena ritorno 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"
Il fatto è che, questo elimina il prodotto, ma solo la prima riga e non quello che si fa clic.
Desidero eliminare il prodotto su cui si fa clic.
Qualcuno può aiutare?
Non è necessario alcun parametro per la chiamata 'delete'. Basta fare $ product-> delete(); '. Inoltre, usa 'DELETE' come metodo ajax, non' POST'. –
@StuartWagner Ho provato anche quello. Il fatto è che cancella la prima riga della tabella, indipendentemente dalla riga cliccata –
Se si restituisce $ product; 'prima della chiamata' delete() 'nel controller e si aggiunge' console.log (msg); 'alla tua chiamata ajax, cosa ottieni? –