Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am getting error sending status code in laravel apide

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 $(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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading