0

It's my first time with JQuery and Ajax validation in Laravel. I'm trying to validate a form using Laravel Request rules. Seems the server validate the fields because it sends me back the errors when I don't fill up the requests ones but when I do it I get this error on the console SyntaxError: JSON Parse error: Unrecognized token '<'

That's the code I wrote:

TechnicianFormRequest

public function rules()
{
    return [
        'nome' => 'required',
        'cognome' => 'required',
        'ruolo_principale' => '',
        'antincendio' => '',
        'primosoccorso' => '',
        'rischioelettrico' => '',
        'lavoroinquota' => '',
        //
    ];

TechnicianController (store method)

public function store(TechnicianFormRequest $request)
{

    $validated = $request->validated();

    $technician = Tecinfo::create($validated);

    return redirect()->action('TechnicianController@index')->with('success', 'Tecnico aggiunto con successo!');
    // return dd($request->all());

}

Ajax Code: (can't paste js code, so I add a pic)

Ajax code image

Thank you to everyone who will help me

Valerio

1 Answer 1

1

You are parsing Json in your ajax but not returning json from your store method

As Per Laravel Documentation:

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function

Use below in your controller to return json

return response()->json([
    'success' => 'Tecnico aggiunto con successo!',
]);
Sign up to request clarification or add additional context in comments.

6 Comments

may I also ask you how can I redirect to the index method?..thank you very much for your help!
@netnull why do you want to redirect it to index method if you are using ajax?
Maybe I'm wrong but how can I show in the list the person I've stored without reload the page ?
thank you @Sehdev for right answer, it saved my time a lot. @netnull in response to your comment about redirecting to index page you can add this line in your ajax success method window.location.href = {{ route('your-index-route-name') }}
@HamidAli sure. Sure, here it is: Unexpected token '{'. Expected a property name. That's what I wrote on my js file under the success part : window.location.href = {{ action('addTechnician') }};
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.