Emad
Emad

Reputation: 638

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.

Upvotes: 6

Views: 26854

Answers (5)

Waleed Mubarik
Waleed Mubarik

Reputation: 93

try this hope it will help you with rendering errors after the relevant fields.

$("#booking_form").submit(function(e){
            e.preventDefault();
            let form_data = $("#booking_form").serialize()
            $(document).find("span.text-danger").remove();
            $.ajax({
                url : "your-url",
                type : "POST",
                data : form_data,
                success : function(response){

                },
                error:function (response){
                    $.each(response.responseJSON.errors,function(field_name,error){
                        $(document).find('[name='+field_name+']').after('<span class="text-strong textdanger">' +error+ '</span>')
                    })
                }
            })
        })

Upvotes: 0

red1
red1

Reputation: 61

You need to remove contentType: "charset=utf-8" from Ajax options to make it work correctly.

Upvotes: 0

Sathishkumar
Sathishkumar

Reputation: 3733

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.

Upvotes: 22

user9452884
user9452884

Reputation: 283

<div id="error_email"></div>

Put this where you want your error to be displayed

and then in your error function

$('#error_email').html('<p>'+ xhr.responseJSON.errors.email[0] + '</p>')

Upvotes: 0

user7747472
user7747472

Reputation: 1952

Validation return JSON response for an AJAX request not as what you have mentioned in your question. You can check in the lara doc And the response you seeing in the console is a JSON array not HTML errors.

So what you can do is, you can catch any error in AJAX and check there itself if there is any error for email,message and so on. Based on that you can display error on the page.

Upvotes: 0

Related Questions