Hello, I'm trying to create a script to delete records in the database using axios, nothing complicated. Howerer I don't know where I'm doing wrong and if I'm missing something because is the first time I'm using axios.
I thought axios was ajax based so I can make an async request, but it doesn't work. I'm also really confused about how to handle the routes and if I need to have a redirect from the controller.
Any help is appreciated.
Form
<form id="history-form" class="d-inline">
{{ csrf_field() }}
<input type="hidden" name="location_id" id="location-id" value="{{ $location->id }}">
<button type="submit" id="location-submit" class="btn btn-danger float-right">Cancella</button>
</form>
Axios script
document.getElementById('history-form').addEventListener('submit', deleteHistory);
function deleteHistory() {
const token = document.head.querySelector('meta[name="csrf-token"]');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
let id = document.getElementById('location-id').value;
axios.delete('/delete-history', {
data: {id: id}
}).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error.response.data)
});
}
Routes
Route::get('/history', 'HomeController@history')->name('history');
Route::post('/delete-history', 'HomeController@deleteHistory');
Controller
public function deleteHistory()
{
$location_id = request("location_id");
Location::where('id',"=",$location_id)->delete();
}