You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中无法通过Ajax提交模态表单删除用户的求助

Hey there, let's dig into why your delete user Ajax call is hitting the error callback even though the status code shows 200. I've gone through your code and spotted several key issues that are likely causing this problem:


1. Mismatched Request Parameter Names

Your controller is looking for full_name and password from the request, but your Ajax call is sending d_full_name and d_password. This mismatch means Auth::attempt() will always fail because it can't find the correct credentials.

2. Broken Response Flow in Controller

You're returning a JSON response before logging the user out and redirecting. Once you return a response, the rest of the code (logout/redirect) never runs. Worse, if Auth::attempt() fails, you don't return any JSON at all—this makes your Ajax call (which expects JSON data) throw an error even with a 200 status.

3. CSRF Token Typo

Your Ajax code tries to get $("#csrf").val(), but your hidden CSRF input has the ID d_csrf. Fortunately, you're already setting the CSRF header via $.ajaxSetup, so this redundant token can be removed entirely.

4. Typo in Stored Procedure Call

You have $$d_time in your stored procedure parameters—this extra $ will cause a PHP error that silently breaks the response.


Fixed Code Snippets

Updated Ajax Script

$(document).ready(function(){
    $('#delete_user').click(function(e){
        e.preventDefault();
        
        $('#final_delete').on('click', function(e) {
            e.preventDefault();
            
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            
            $.ajax({
                method:"POST",
                url:"delete_user",
                cache: false,
                processData:true,
                contentType: 'application/x-www-form-urlencoded',
                data:{
                    'id' : $('#d_id').val(),
                    'full_name' : $('#d_full_name').val(), // Matches controller parameter
                    'password' : $('#d_password').val() // Matches controller parameter
                },
                dataType :"JSON",
                success:function(response){
                    if(response.success){
                        swal({
                            title: "User deleted Successfully",
                            text: "You will now be logged out. Sorry to see you go!!",
                            icon: "warning",
                            buttons: true,
                            dangerMode: true,
                        }).then(() => {
                            window.location.href = '/login'; // Handle redirect in frontend
                        });
                    } else {
                        swal({
                            title: "Oops! Authentication Failed",
                            text: response.message || "Your name or password is incorrect",
                            icon: "error",
                            buttons: true,
                            dangerMode: true,
                        });
                    }
                },
                error:function(e){
                    swal({
                        title: "Oops! Some Error",
                        text: "Please try again later",
                        icon: "warning",
                        buttons: true,
                        dangerMode: true,
                    });
                    console.log("Server Response:", e.responseText); // Log raw response for debugging
                },
            });
        });
    });
});

Updated Controller Code

use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

public function delete_user(Request $request){
    // Validate incoming request first
    $request->validate([
        'id' => 'required|integer',
        'full_name' => 'required|string',
        'password' => 'required|string'
    ]);

    date_default_timezone_set("Asia/Kolkata");
    $d_time = date("Y-m-d,H:i:s ");
    
    try {
        $user = \App\User::findOrFail($request->id);
        
        // Verify credentials manually (since Auth::attempt uses email by default)
        if($user->full_name === $request->full_name && Hash::check($request->password, $user->password)){
            // Fix the typo in $d_time
            DB::select('CALL my_stored_procedures(?,?,?,?,?,?,?,?,?,?,?,?)', 
                array("DELETE", $user->id, "", "", "", "", "", $d_time, "", "", "", $d_time)
            );
            
            Auth::logout();
            Session::flush();
            
            return response()->json([
                'success' => true,
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Full name or password is incorrect'
            ], 422); // Return validation error status code
        }
    } catch (\Exception $e) {
        Log::error('Delete user error:', ['error' => $e->getMessage()]);
        return response()->json([
            'success' => false,
            'message' => 'Server error occurred'
        ], 500);
    }
}

Debugging Tips

  • Add Log::info('Delete user request data:', $request->all()); at the start of your controller method to confirm you're receiving the right parameters.
  • Check your Laravel log file (storage/logs/laravel.log) for any silent errors from the stored procedure or database calls.
  • In the Ajax error callback, log e.responseText—this will show you exactly what the server is returning, even if it's not valid JSON.

内容的提问来源于stack exchange,提问作者Skumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:37:37