F
F
FimozMozga2020-04-21 09:28:25
Laravel
FimozMozga, 2020-04-21 09:28:25

How to fix 422 Ajax and Laravel error?

Hello.
I get this error 422 (Unprocessable Entity), I googled it seems like the error is related to data validation, but I messed up somewhere.

<script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $( "#form" ).submit(function( e ) {
            e.preventDefault();

            var message = $('#message').val();
            var img = $('#img').val();
            var user_id = $('#user_id').val();
            var _token = $('input[name="_token"]').val();

            $.ajax({
                type: "POST",
                url: "{{route('profile.store', ['id' => Auth::user()->id])}}",
                data: {message:message, img:img, user_id:user_id, _token:_token},
                success: function (data) {
                    $("#textpost").html($(data).find("#textpost").html());
                },
            });
        });

    </script>


The method itself
public function store(Request $request) {
        $validator  = $this->validate($request,[
            'message' => 'required|max:1000',
            'img' => 'mimes:jpeg,png,gif|max:3000',
        ]);

        if($validator ) {
            $post = new Profile();
            $post->message = $request->message;
            $post->user_id = Auth::user()->id;

            if($request->file('img')) {
                $path = Storage::putFile('public', $request->file('img'));
                $url = Storage::url($path);
                $post->img = $url;
            }

            $post->save();
        }

        return redirect()->back();
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-04-21
@FimozMozga

The data you submit is not validated:

[
    'message' => 'required|max:1000',
    'img' => 'mimes:jpeg,png,gif|max:3000',
]

Since we don't know the details, we can't help you any further. Understand what each of these rules does, what you are sending and understand what the problem is. In the response, you should receive a description of the errors, indicating the fields and specific rules.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question