简体   繁体   中英

Ajax validation and SyntaxError: JSON Parse error: Unrecognized token '<' on Laravel

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

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!',
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM