R
R
Roman2020-02-27 21:34:01
Laravel
Roman, 2020-02-27 21:34:01

How to correctly implement form validation in Laravel 6 when submitting it using AJAX?

Good afternoon. Help me understand the sequence of form validation when submitting a form via AJAX (laravel 6)

1. In AJAX, I take data from the form using and pass it on the form action. 2. This data is received in the controller and sent to the validator$('#form').serialize()

Validator::make($request->all(), [
    // правила
])->validate();

3. If the checks fail, then the validator generates JSON with errors and sends them back. Errors are processed using JS and displayed.

4. If there are no errors, how to correctly redirect to the initial form? If it was a regular check, without AJAX, I would write
return back()->with('message', 'Изменения сохранены.');
after validation in the controller. How to implement the code above in JS? (redirect to the initial and entry to the session).

5. Is there a CSRF check when submitting a form using AJAX?

6. Is everything being implemented correctly, is there anything else that needs to be done or some additional checks. Thanks for the clarification, I would like to hear the opinion of knowledgeable people.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Kulaxyz, 2020-02-27
@gagablik

Read about form request, and remove Validator::make from the controller. After the main section of code, write

return response()->json(['message' => 'изменено'] ,200);

In the same way, you can pass any parameters in the response and on the client you get the response and access response.data.
You must have a csrf meta field in the head and add its value as a header, otherwise it will simply throw out a 419 error.

J
Just Me, 2020-02-28
@Just__Den

2.

public function update(Request $request, Post $post, $id)
    {

        $request->validate([ 
           // rules
        ]);

        // действия с БД

        return response()->json([
            'status' => true,
            'message' => 'данные изменены'
        ]);
        
    }

4. Where will you redirect to in ajax? The meaning of ajax is that sending without redirects and reloading
5. Yes. Attach csrf to the header as specified in the documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question