Handling Error Response Messages in Laravel App Using Ajax

Β·

4 min read

Handling Error Response Messages in Laravel App Using Ajax

Hello World πŸ‘¨πŸ½β€πŸ«,

Here's a quick tutorial where am going to show you a code snippet on how you can handle error response messages from your validation on the server side of your Laravel application using Ajax and a custom JavaScript function which allows you to show all error messages triggered by your validation rules at once on each fields your user has an error like the screenshot above.

HTML

Alright here we go, the first thing I think every developer does when carrying out CRUD operations is set up a Html form where their users can input some records and add some basic client side validation using some html attributes or JavaScript to quickly notify the user of an error. But now am not going to have any client side validation rules or attributes on my Html input form element, with that in mind here's how I will set up my Html input form element πŸ‘‡πŸ½

<div class="form-group">
        <label>Book title</label>
        <input type="text" class="el" 
         name="book_title">
        <span class="book_title" style="color:red;font-size:12px;"> 
        </span>
</div>

Okay buddy πŸ˜‰, that's quite simple but here's something you should take note of. if you notice, the span tag has a class="book_title" attribute value same with the input tag name="book_title" attribute value, that's because we are following a convention which allows us to show or render each error message under the right input field with that error. One more thing to take note of is the input tag class="el" attribute value. That enables us to query and validate all the input fields in our DOM using our JavaScript code.

Laravel

Let's say you have a basic validation rule set up on your Laravel controller like this πŸ‘‡πŸ½

 $validator = Validator::make($request->all(), [
        'book_title' => 'required',
]);

if($validator->fails()) {
     return response()->json($validator->errors()); // error response message
}

Alright yeah I have something like that on my controller so what's next πŸ€”?

Okaay calm down here's what we will do, we will set up a short custom JavaScript function to handle the error response message from our Laravel controller method and have the errors shown on the client side.

JavaScript

function handleError(response) {

        let input = document.querySelectorAll('.el'); // get all the input fields with the class `.el`

        input.forEach( (field) => {

               let errorElement = document.querySelector('.'+field.name); // this will get any element (in our case span tag) that the class attribute value is same with the input tag name attribute value

               // check if the input field has an error

               if(response.hasOwnProperty(field.name)) {

                      errorElement.innerHTML = response[field.name]; // replace the text content of the span tag with the error response message

                } else {

                      errorElement.innerHTML = ''; // else leave it empty or set it to display none.

                }

        } );

}

Hmm πŸ€”πŸ€”πŸ€”??

Okay let's go through the code together😁. So the first thing we did was to create a function handleError. This function has a parameter which is going to be an Array or JSON response message from our controller. Next we got all the input fields (in our case a single field) with the class="el" in our HTML code, to get each element in the nodeList we did an iteration on the input variable. While iterating through the nodeList we got the span tag which will show the error message to the user. And finally we checked for the input fields whose error exists in the Array or JSON response message from our controller. If an error exists, show it to the user else it doesn't exist, hide the element.

So friends that explains it. The next thing we want to do is to actually call the handleError function on our Ajax success callback function like this πŸ‘‡πŸ½

let's say you're using JQuery Ajax

$.ajax({
      url : '/books/create', // route to your controller
      method : 'POST',
      processData : false,
      contentType : false,
      data : yourFormData,
      success : (response) => {
           // handle success response here
      },
     error  : (error) => {
            if(error.statusCode == 422) {
                handleError(error) 
            }   
     }
})

Let's run a test..... okay here's what we gat πŸ‘‡πŸ½

book[1].JPG

That's it buddy, Phew we made it to the end πŸ˜ͺ. Thanks for reading.