Home > OS >  Laravel form validation from ajax returns error
Laravel form validation from ajax returns error

Time:11-07

I am trying to insert data into db using ajax. Before that I need to validate the form. I am passing form data as serialized to the controller. But when I am trying to validate it gives me error like "The given data was invalid."

Here is my code

ajax function

$('#btn-save-appointment').on('click', function(e) {
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        }
    });
    
    jQuery.ajax({
        url: "/saveAppointment",
        method: 'post',
        data: { formdata: $('#appointment-event').serialize() },
        cache: false,
        processData : false,
        success: function(result){ 
          console.log('form: ' result);            
        
        }
    });
 });

Controller

public function saveAppointment(AppointmentStoreRequest $request) {         
    $validated = $request->validated();
    dd($validated);
}

AppointmentStoreRequest

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class AppointmentStoreRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }
   public function rules()
   {
    return [
        'category' => 'required',
        'treatments' => 'required',
        'time-in-minutes' => 'required',
        'treatmentsRooms' => 'required',
        'date' => 'required',
        'time' => 'required',
        'gender' => 'required',
        'first_name' => 'sometimes|required',
        'last_name' => 'sometimes|required',
        'dob' => 'sometimes|required',
        'insurance' => 'sometimes|required',
        'phone' => 'sometimes|required',
        'email' => 'sometimes|required|email'
    ];
   }
 }

CodePudding user response:

Remove the { formdata: ... } from your data property:

data: $('#appointment-event').serialize(),
  • Related