I'm trying to make a DOM event where the user clicking a table row's header ( th
) cell will delete the corresponding row from the database that supplies the table's data.
This code worked as intended framework-less, by just POST'ing an AJAX containing the row's id info from index.php to delete.php which then ran a sql query.
However, after moving the site to Laravel I ran into an error:
POST http://sandbox.app/delete 419 (unknown status)
The JavaScript piece responsible for attaching the delete event and posting the id through AJAX:
function attachDelete() {
$("#mainTable tbody tr th").on("click", function(e){
console.log(e.target.innerText + " was clicked");
var token = $('meta[name="csrf-token"]').attr('content');
var id_to_delete = e.target.innerText;
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
dataType: 'text',
url: 'delete',
data: {
'id_to_delete': id_to_delete,
"_method": 'POST',
"_token": token
},
success: function () {alert("Deleted!"); },
failure: function() {alert("Error!");}
});
});
}
attachDelete();
The console.log(e.target.innerText + " was clicked");
goes off.
However, the success
/ error
messages do not appear.
Going to http://sandbox.app/delete directly brings up a Laravel error window with lots of text, and this part highlighted:
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
I've added the token variables after reading answers to related questions on StackOverflow. This didn't help.
In case it matters, the route:
Route::post('/delete', 'TasksController@delete');
The controller :
class TaskController extends Controller
{
public function delete()
{
include 'config.php';
$stmt = $pdo->prepare('DELETE FROM food WHERE id = :id');
$stmt->execute(['id' => $_POST['id_to_delete']]);
}
}
The code inside delete() used to just be the contents of a delete.php file in the old, framework-less site, where everything worked.
I've tried doing it without the controller by creating a delete.php view (with the same code as the delete() function). It didn't make a difference though:
Route::post('/delete', function () {
return view('delete');
});
Well, it seems if you are communicating with POST at the backend. So, you should be configuring your routes on the api.php instead of web.php
Place your route associated with controller
Route::post('/delete', 'TasksController@delete');
Inside api.php file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.