2016-09-06 21 views
8

Tôi đang cố gắng xóa bản ghi bằng ajax trong laravel 5.3, tôi biết đây là một trong những câu hỏi phổ biến và đã có rất nhiều giải pháp trực tuyến và hướng dẫn có sẵn về chủ đề này. Tôi đã thử một số trong số họ nhưng hầu hết cho tôi lỗi tương tự NetworkError: 405 Method Not Allowed. Tôi đã cố gắng làm nhiệm vụ này bằng góc độ khác nhau nhưng tôi bị kẹt và không thể tìm thấy nơi tôi sai, đó là lý do tại sao tôi thêm câu hỏi này cho hướng dẫn.Làm thế nào để xóa bản ghi trong laravel 5.3 bằng cách sử dụng yêu cầu ajax?

Tôi đang thử tập lệnh sau để xóa bản ghi.

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}', '[email protected]'); 

Trong Xem

<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"); 
    }); 

Khi tôi bấm vào nút delete nó trở về tôi lỗi NetworkError: 405 Method Not Allowed trong giao diện điều khiển. Nếu không có chức năng xóa cùng ajax sẽ hoạt động bình thường.

Bất cứ ai có thể hướng dẫn tôi nơi tôi sai rằng tôi có thể khắc phục vấn đề, tôi muốn đánh giá cao nếu có ai đó hướng dẫn tôi về vấn đề này. Cảm ơn bạn ..

Trả lời

13

Thay vì sử dụng Route::get hãy sử dụng Route::delete.

Ngoài thay đổi đó, type: 'Put' đến type: 'DELETE' trong cuộc gọi ajax.


P.S. Mã này

$Users = new UserModel;  // Totally useless line 
$Users = UserModel::find($id); // Can chain this line with the next one 
$Users->delete($id); 

có thể được viết như sau:

UserModel::find($id)->delete(); 

Hoặc thậm chí ngắn hơn:

UserModel::destroy($id); 
+0

Cảm ơn bạn đã hướng dẫn, tôi đã làm theo hướng dẫn của bạn nhưng vẫn gặp phải vấn đề tương tự. –

+0

Bạn đã thử sử dụng 'loại: 'DELETE'' trong cuộc gọi ajax của mình chưa? – siannone

+0

Hãy để tôi kiểm tra nó –

1

tôi đang khôi phục một dòng chảy lao động xóa, với một động từ theo yêu cầu.Hy vọng nó giúp

và theres một mã số nhận xét trong bộ điều khiển có thể xử lý một yêu cầu ajax

Trong hình thức (với lưỡi):

{{ 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\[email protected]']); 

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'); 
    } 

Trong phần chuyển hướng, tôi sẽ trở lại trang danh sách của tôi (admin.products) với một notifier thành công. Tuyến đường sẽ là:

Route::get('admin/products', ['as' => 'admin.products', 'uses' => 'Product\[email protected]']); 

Vì vậy, bạn có thể hoàn thành luồng.

1

Hãy chắc chắn để thêm video này trong thẻ meta của tầm nhìn của bạn

<meta name="csrf-token" content="{{ csrf_token() }}"> 

Trong Routes của bạn, làm điều này

Route::delete('/user/delete/{id}', '[email protected]'); 

Trong điều khiển của bạn, làm điều này

UserModel::destroy($id); 

hoặc

DB::table('table_name')->where('id', $id)->delete(); 

Vì đó là yêu cầu delete, bạn sẽ phải gửi csrf_token cùng với tiêu đề ajax làm trạng thái trang web chính thức. https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token

Hãy chắc chắn để thêm video này trước khi cuộc gọi ajax

$.ajaxSetup({ 
     headers: { 
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
     } 
}); 

Bây giờ gửi yêu cầu

$(".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 
     } 
    }); 
}); 

Tôi hy vọng điều này sẽ giúp.

Các vấn đề liên quan