Home > OS >  I am getting error sending status code in laravel apide
I am getting error sending status code in laravel apide

Time:07-16

When sending response code in laravel api, validation does not enter. I can view it from the network, but when I send the status code, the console prints an error and I cannot print the validations on the blade page. If I don't send status code I can print validations.

Following my code: StudentController

 public function store(Request $request): object
    {
        $validate = Validator::make($request->all(),[
            'name' => 'required',
            'course' => 'required',          
        ]);
        $data = [
            'name' => $request->name,
            'course' => $request->course,           
        ];
        if ($validate->fails()){
            return response()->json(['success' => false, 'errors' => $validate->messages()->all()],422);
        }
        Student::insert($data);
        return response()->json(['success' => true, 'message' => "Registration Successful"]);
    }

ajax

 $(document).ready(function (){
       $('#createBtn').on('click',function (e) {
          e.preventDefault();
          let form = $('#student-add').serialize();

          $.ajax({
             'url': "{{ route('students.store') }}",
             'data': form,
             'type': "POST",
             success:function (result) {
                 $('#ajax-validate ul').text("");
              if(result.success === true){
                  console.log("True");
              }else {
                  result.errors.forEach(function (item) {
                      $('#ajax-validate ul').append('<li>' item '</li>');
                  });
              }
             }
          });
       });
    });

console

enter image description here

network

enter image description here

CodePudding user response:

You have your response.errors.forEach inside of your success: function(), but 422 (or any 400) code doesn't get handled by the success function, but rather the error function:

$(document).ready(function () {
  $('#createBtn').on('click', function (e) {
    e.preventDefault();

    let form = $('#student-add').serialize();
    
    $.ajax({
      url: "{{ route('students.store') }}",
      data: form,
      type: 'POST',
      success: function (result) {
        if (result.success === true) {
          // Do whatever on `2XX` HTTP Codes
        }
      },
      error: function (response) {
        if (response.status === 422) {
          let responseJson = response.responseJSON ? response.responseJSON : { errors: [] };

          $('#ajax-validate ul').text('');
          responseJson.errors.forEach(function (item) {
            $('#ajax-validate ul').append('<li>' item '</li>');
          });
        } else {
          console.log('Unhandled Error:', response)
        }
      }
    });
  });
});

Now when an 422 error is explicitly triggered, you code can properly handle the validation errors.

  • Related