Laravel ajax 422 Unprocessable Entity even when token is matching

前端 未结 4 1955
青春惊慌失措
青春惊慌失措 2020-12-19 22:14

I\'m getting 422 Unprocessable Entity error even when I\'m submitting my form via Ajax.

My javascript file

$.ajaxSetup({
    headers         


        
4条回答
  •  猫巷女王i
    2020-12-19 22:48

    I don't think that csrf token is the issue here. If it were you would get TokenMissmatchException and not Unprocessable Entity. Do you happen to have a request validator in your Controller like this?

        $validator = Validator::make($request->all(), [
    
                'username' => 'required|max:30|min:6|unique:users',
    
                'email' => 'required|email|max:50|unique:users',
    
                'password' => 'required|confirmed|min:6',
    
            ]);
    

    If so maybe you can do something like this:

        if ($validator->fails()) {
    
                if($request->ajax())
                {
                    return response()->json(array(
                        'success' => false,
                        'message' => 'There are incorect values in the form!',
                        'errors' => $validator->getMessageBag()->toArray()
                    ), 422);
                }
    
                $this->throwValidationException(
    
                    $request, $validator
    
                );
    
            }
    

    After that you can catch validation errors in your ajax error handler like this:

      $('.keywords-plan-form').submit(function(event) {
           event.preventDefault();
    
    $.ajax({
        url: '/laravel/public/keywordsplans',
        type: 'POST',
        data: $(this).serialize(),
        success: function(data){
            alert(data);
            // success logic
        },
        error: function(jqXhr, json, errorThrown){// this are default for ajax errors 
            var errors = jqXhr.responseJSON;
            var errorsHtml = '';
            $.each(errors['errors'], function (index, value) {
                errorsHtml += '
    • ' + value + '
    '; }); //I use SweetAlert2 for this swal({ title: "Error " + jqXhr.status + ': ' + errorThrown,// this will output "Error 422: Unprocessable Entity" html: errorsHtml, width: 'auto', confirmButtonText: 'Try again', cancelButtonText: 'Cancel', confirmButtonClass: 'btn', cancelButtonClass: 'cancel-class', showCancelButton: true, closeOnConfirm: true, closeOnCancel: true, type: 'error' }, function(isConfirm) { if (isConfirm) { $('#openModal').click();//this is when the form is in a modal } }); } }); });

    And see the messages in the modal message

提交回复
热议问题