Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show all laravel validation errors in one div when using jQuery ajax

I'm using this ajax request to send request using jQuery:

 $.ajax({type: 'POST',
             url: '/send-review',
             data: {
                 "_token": "{{ csrf_token() }}",
                 "_id": {{$item->id}},
             },
             success: function (data) {
                 console.log(data);
             },
             error: function (err) {if (err.status == 422) { 
// when status code is 422, it's a validation issue

        }
    }
   });

I can show get Laravel validation error in the bottom of each input, but how can I show all of the Laravel validation errors format in one box of HTML using jQuery?

like image 761
Majid Jalilian Avatar asked Sep 08 '25 16:09

Majid Jalilian


2 Answers

There are lots of way you can show messages . You can print error object . like as

var htmlErr= []
var err.errors.map((data,index)=>{
   $(".comment").text(data.comment);  
});

in html

<p class="comment"></p>

then you can try with like this. For more error message more class ..

Its just dummy code for accurate code i need to know details about your data/object.

like image 181
Sagar Roy Avatar answered Sep 10 '25 08:09

Sagar Roy


laravel 8

I always use this :

$.ajax({type: 'POST',

             ...

             success: function (data) {
                 console.log(data);
             },
             error: function (err) {
               if (err.status == 422) { 
                   toastError(err.responseJSON.message);
                   let details = res.responseJSON.errors ;
                   Object.keys(details).forEach(field => {
                      formatErrorUsingClassesAndPopover(field,details[field]);
                   });
               }
            }
        });

And for Formatting the answer implement the formatErrorUsingClassesAndPopover( element , array_of_problems ) make it as abstract as possible . for example (Using Bootstrap and jQuery):

 function formatErrorUsingClassesAndPopover(element , array_of_problems ){
       let someHTML = '';
       array_of_problems.forEach(function(e){someHTML+='<li>'+e+'</li>'});
       $('#'+element+'_error_section').html('<ul>'+someHTML+'</ul>');
       $('#'+element).addClass('is-invalid');
 }

 ...

 //don't forget to use this in the ajax success function :
 $('input').removeClass('is-invalid');//or you can let the client side validation do it 

Note : To copy past this code you need that if your database column is `field` ,you need :
  • your error section's id to be field_error_section .
  • your input's id to be field .
like image 22
Yasser CHENIK Avatar answered Sep 10 '25 09:09

Yasser CHENIK