Search code examples
javascriptjquerylaravelajaxform

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


Solution

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