Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display Laravel validation errors with AJAX

I have a Form in Laravel that submits with Ajax.every thing works well but the problem is that I can't render the validation's errors in HTML.
(I want to display the errors in <ul><li> in my HTML)

Here is my Ajax request:

 $(document).ready(function () {
        $("#submit").click(function (xhr) {
            xhr.preventDefault(),
                $.ajax({
                    type: "POST",
                    contentType: "charset=utf-8",
                    dataType: 'json',
                    url: "{{route('messages.store')}}",
                    headers: {
                        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
                    },
                    data: {
                        name: $("#name").val(),
                        email: $("#email").val(),
                        phone: $("#company").val(),
                        subject: $("#subject").val(),
                        message: $("#message").val()
                    },
                    success: function () {
                        alert('True');
                    },
                    error: function (xhr) {
                        console.log((xhr.responseJSON.errors));
                    }
                }, "json")
        })
    });

Console logs:

screenshot

Thanks for any help.

like image 952
Emad Avatar asked Mar 17 '18 18:03

Emad


1 Answers

Try like this

error: function (xhr) {
   $('#validation-errors').html('');
   $.each(xhr.responseJSON.errors, function(key,value) {
     $('#validation-errors').append('<div class="alert alert-danger">'+value+'</div');
 }); 
},

Here validation-errors is the div id. You can use your own div id.

like image 108
Sathishkumar Rakkiyasamy Avatar answered Sep 20 '22 11:09

Sathishkumar Rakkiyasamy