Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

forms - Laravel ajax 422 Unprocessable Entity even when token is matching

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

My javascript file

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

$('.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(data){
            // Error...
            var errors = $.parseJSON(data.responseText);

            console.log(errors);

            $.each(errors, function(index, value) {

            });

        }
    });

});

as you can see I added X-XSRF-TOKEN****strong text to ajax header.

This is my '' tag

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

my Form Data in chrome debuger

_token:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
date:
keyword[0]:Lorem ipsum
keyword[1]:Is dolor amet
keyword[2]:plumber tampa

Request Headers

X-XSRF-TOKEN:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
.....

am I doing something wrong or forgetting something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
        });
        //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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...