6

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.

0

5 Answers 5

22

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.

Sign up to request clarification or add additional context in comments.

5 Comments

It does not come inside success response it come as error but yeah that will wok
Can you please add the PHP code to understad why it is coming to error block?.
Thank you @Sathishkumar, that's exactly what I was looking for.
Please check my updated answer. I have added $('#validation-errors').html('') to clear the existing error messages.
@Eмαd Welcome ;)
0

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.

Comments

0
<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>')

Comments

0

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

Comments

0

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>')
                    })
                }
            })
        })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.