개발/Laravel

Laravel Ajax Form Validation

Sengwoolee 2020. 7. 21. 00:53

1. Ajax Form Validation 요청

<script>
$(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")
        })
});
</script>

2. Validation Error 표시

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