Home > OS >  How can I delete using ajax in laravel?
How can I delete using ajax in laravel?

Time:09-23

BLADE FILE

<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
                                            </td>

AJAX

$(document).ready( function () {
        $(".deleteuser").click(function(){
        var id = $(this).data("id");
        var token = $(this).data("token");
        $.ajax(
        {
            url: "user/delete/" id,
            type: 'DELETE',
            dataType: "JSON",
            data: {
                "id": id,
                "_method": 'DELETE',
                "_token": token,
            },
            success: function ()
            {
                console.log("it Work");
            }
        });

        console.log("It failed");
    });
});

CONTROLLER

public function destroyuser($id){  
        $this->authorize('Admin'); 
        User::find($id)->delete($id);
        return response()->json([
        'success' => 'Record has been deleted successfully!'
        ]);
        return view('viewuser');
    }

If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance

CodePudding user response:

You can replace your url as this and check:

var id = data.id;

var url = "{{route('your_route',":id") }}";

url = url.replace(':id', id);

pass url in your ajax url param

Or make above changes:

BLADE FILE

<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>

SCRIPT

<script>
  $(document).ready(function() {
    
    $(document).on('click', '.delete', function ()
    {
      var obj = $(this);
      var id=$(this).closest('td').find(".delete_id").val();
      var result = confirm("Are you sure want to delete?");
      if(result)
      {
        $.ajax(
        {
          type: "POST",
          url: "{{route('delete_method')}}",
          data: {
            '_token': $('input[name="_token"]').val(),
            'id': id
          },
          cache: false,
          success: function (data)
          {
            if (data.status === 'success')
            {
              window.location = "{{route('redirect_route')}}";
              toastr["success"]("Deleted Successfully", "Success");
            } 
            else if (data.status === 'error')
            {
              location.reload();
              toastr["error"]("Something went wrong", "Opps");
            }
          }
        });
      }
    });
  });
</script>

Controller

public function delete_method(Request $request)
    {
        $del = ModelName::findOrFail($request->id)->delete();

        if($del)
        {
            return response()->json(['status' => 'success']);
        }
        else{
            return response()->json(['status' => 'error']);
        } 
    }

Route

Route::post('/test/delete','TestController@delete_method')->name('delete_method');

CodePudding user response:

In your ajax codes, change this:

url: "user/delete/" id,

To:

url: "{{ url('user/delete') }}/"   id

If your ajax codes are inside of your blade file also you can use this way:

url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"

CodePudding user response:

  1. I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.

    $(document).ready( function () {console.log("document is ready")
    $(".deleteuser").click(function(){
    

Refresh the page and check if "document is ready" is logged to the console. If it isn't then the javascript is not loading

  1. Check if the route is properly defined

CodePudding user response:

You incorrectly define delete function! change

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

To

 User::find($id)->delete();
  • Related