可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm trying to delete record using ajax in laravel 5.3, i know this is one of the common question and there is already lots of online solutions and tutorials available about this topic. I tried some of them but most of giving me same error NetworkError: 405 Method Not Allowed
. I tried to do this task by different angle but i'm stuck and could not found where i'm wrong, that's why i added this question for guideline.
I'm trying following script for deleting the record.
Controller.php
public function destroy($id)
{ //For Deleting Users
$Users = new UserModel;
$Users = UserModel::find($id);
$Users->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
}
Routes.php
Route::get('/user/delete/{id}', 'UserController@destroy');
In View
<button class="deleteProduct" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >Delete Task</button>
App.js
$(".deleteProduct").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'PUT',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
When i'm click on delete button it returning me error NetworkError: 405 Method Not Allowed
in console. Without ajax same delete function is working properly.
Can anyone guide me where i'm wrong that i can fix the issue, i would like to appreciate if someone guide me regarding this. Thank You..
回答1:
Instead of using Route::get
use Route::delete
.
In addition to that change the type: 'Put'
to type: 'DELETE'
in the ajax call.
P.S. This code
$Users = new UserModel; // Totally useless line
$Users = UserModel::find($id); // Can chain this line with the next one
$Users->delete($id);
can be written as:
UserModel::find($id)->delete();
Or even shorter:
UserModel::destroy($id);
Keep in mind that ->delete()
will fire an event while ::destroy()
will not.
回答2:
Make sure to add this in the meta
tag of your view
<meta name="csrf-token" content="{{ csrf_token() }}">
In your Routes
, do this
Route::delete('/user/delete/{id}', 'UserController@destroy');
In your controller, do this
UserModel::destroy($id);
or
DB::table('table_name')->where('id', $id)->delete();
Make sure to check that the user who is deleting the account actually owns the account a.k.a run authorization test.
Since it's a delete
request, you would require to send the csrf_token
along with your ajax header as the official site states.
https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token
Make sure to add this before the ajax call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Now send the request
$(".deleteProduct").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax(
{
url: "user/delete/"+id,
type: 'delete', // replaced from put
dataType: "JSON",
data: {
"id": id // method and token not needed in data
},
success: function (response)
{
console.log(response); // see the reponse sent
},
error: function(xhr) {
console.log(xhr.responseText); // this line will save you tons of hours while debugging
// do something here because of error
}
});
});
I hope this helps.
回答3:
$(".deleteProduct").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE', // Just delete Latter Capital Is Working Fine
dataType: "JSON",
data: {
"id": id // method and token not needed in data
},
success: function (response)
{
console.log(response); // see the reponse sent
},
error: function(xhr) {
console.log(xhr.responseText); // this line will save you tons of hours while debugging
// do something here because of error
}
});
});
回答4:
i'm resuming a working flow of deletion, with a request VERB. Hope it helps
and theres a commented code in the controller that could handle an ajax request
In the form (with blade):
{{ Form::open(['method' => 'DELETE', 'route' => ['admin.products.edit', $product->id], 'name' => 'delete']) }}
{{ Form::close() }}
Route:
Route::delete('admin/products/{id}/edit', ['as' => 'admin.products.edit', 'uses' => 'Product\ProductController@delete']);
ProductController:
public function delete($id)
{
// if (Request::ajax()) {
// if (Request::isMethod('delete')){
$item = Product::findOrFail($id);
$item->delete();
return redirect()->route('admin.products')->with('flashSuccess', 'deleted');
}
In the redirect part, i'm going back to my list page (admin.products) with a success notifier. The route would be:
Route::get('admin/products', ['as' => 'admin.products', 'uses' => 'Product\ProductController@getList']);
So you can complete the flow.