This is my route in web.php :
Route::get('/delete_row/id', 'MyController@delete_row');
In controller MyController:
delete row from months table in database.
public function delete_row($id)
{
DB::table('months')->where('id_month', $id)->delete();
return back();
}
In view :
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>The table element</h1>
<table>
<tr>
<th>Month</th>
<th>delete row</th>
</tr>
<tr>
<td>January</td>
<td>
<form method="get" action="/delete_row/1">
<button type="submit"> delete</button>
</form>
</td>
</tr>
<tr>
<td>February</td>
<td>
<form method="get" action="/delete_row/2">
<button type="submit"> delete</button>
</form>
</td>
</tr>
</table>
</body>
</html>
I want to refresh only the row or table, not the whole page. please how can do that with javascript or anything else?
CodePudding user response:
You can achieve this via AJAX
. Here's how.
First of all, your route definition is incorrect since your id
is gonna be dynamic. And you should use a post request.
Change your route in web.php
to this instead:
Route::post('/delete_row/{id}', 'MyController@delete_row')->name('row.delete');
// This is so your id parameter can be any value at all. I also gave it
// a name so we can access it with the route() method
Now change your controller to give a JSON
response instead, this way:
public function delete_row($id)
{
DB::table('months')->where('id_month', $id)->delete();
return response()->json(['success' => 'Deleted successfully']);
Now in you view/blade file, there is absolutely no need to use html forms, since you are gonna be making use of AJAX
Change it to this:
<!DOCTYPE html>
<html>
<head>
<meta name="csrf_token" content="{{ csrf_token() }}">
{{-- Add crsf token so your ajax request will be allowed --}}
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>The table element</h1>
<table>
<tr>
<th>Month</th>
<th>delete row</th>
</tr>
<tr>
<td>January</td>
<td>
<button data-id="1" type="submit"> delete</button>
</td>
</tr>
<tr>
<td>February</td>
<td>
<button data-id="2" type="submit"> delete</button>
</td>
</tr>
</table>
<script>
// here is your ajax script
$('.delete-button').click(function() {
var id = $(this).data('id');
var el = this;
var url = "{{ route('row.delete', ':id') }}";
var token= $('meta[name="csrf_token"]').attr('content');
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'POST',
data: {'_method' : 'POST', '_token' :token},
dataType: 'json'
})
.done(function(response){
$(el).closest('tr').css('background','red');
$(el).closest('tr').fadeOut(900,function(){
$(this).remove();
});
})
.fail(function(){
// Do nothing
});
});
</script>
</body>
</html>