简体   繁体   中英

Display error message in Modal using Ajax, laravel

I'm new to Laravel, I have a problem displaying errors on my project. I'm using laravel request for validation and AJAX to submit form inside a modal. I would like to see the error message for each field that are inputted incorrectly. However, I'm getting this error:

The Given data is invalid

I checked the network tab, and I'm seeing the errors there but I can't figure out why this is not showing in my fields.

Here's the error: 在此处输入图像描述

Here's my Ajax

//add user code here
$(document).on("click", "#addUserBtn", function (e) {
    e.preventDefault();
    const first_name = $("#addModal [name=first_name]").val();
    const middle_name = $("#addModal [name=middle_name]").val();
    const last_name = $("#addModal [name=last_name]").val();
    const email = $("#addModal [name=email]").val();
    const cellphone = $("#addModal [name=cellphone]").val();
    const userType  = $("#addModal [name=user_type]").val();
    const payload = {
        first_name: first_name,
        middle_name: middle_name,
        last_name: last_name,
        email,
        cellphone,
        user_type: userType
    }
    $("#addModal .fa-spinner").removeClass('d-none');
    $.ajax({
        url: "/users-listing",
        data: payload,
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    }).done(function(res) {
        $("#addModal .fa-spinner").addClass('d-none');
        $("#addModal .form-message-container").html(res.message).addClass('text-success').fadeIn(1000);
        table.draw(false);
        setTimeout(() => {
            $("#addModal .form-message-container").html('').removeClass('text-success').fadeOut();
            $("#addModal [name=first_name]").val('');
            $("#addModal [name=middle_name]").val('');
            $("#addModal [name=last_name]").val('');
            $("#addModal [name=email]").val('');
            $("#addModal [name=cellphone]").val('');
            $("#addModal #closeModal").click();
        }, 3000);
    }).fail(function(err) {
        $("#addModal .fa-spinner").addClass('d-none');
        $("#addModal .form-message-container").html(err.responseJSON.message).addClass('text-danger').fadeIn(5000);
        setTimeout(() => {
            $("#addModal .form-message-container").html('').removeClass('text-danger').fadeOut();
        }, 5000);
    });
});


// code end here

Here's my controller "Store"

public function store(UserRequest $request)
{
    $data = $request->all();

    $data['password'] = Hash::make(Str::random(10));
    $data['status'] = 1;
    $user = User::create($data);
    $user->sendPasswordResetNotification(Str::random(60));
    return response()->json(['code' => 200, 'message' => 'User added succesfully'], 200);
    exit;
}

Request code

    public function rules()
{
    return [
        'id'          => 'bail|nullable',
        'first_name'  => 'required|string|min:2',
        'middle_name' => 'string|nullable',
        'last_name'   => 'required|string|min:2',
        'user_type'   => 'required',
        'cellphone'   => ['nullable','max:15', Rule::unique('users', 'cellphone')->whereNull('deleted_at')->ignore($this->id, 'id')],
        'email'       => ['required', 'email', Rule::unique('users', 'email')->whereNull('deleted_at')->ignore($this->id, 'id')],
        'status'      => 'numeric'
    ];
}

My blade code

<div class="modal-body m-2">
                <form id="adduserForm">
                {{ csrf_field() }}
                    <div class="row form-group">
                        <div class="col">
                            <label>First name</label>
                            <input name="first_name" id="first_name" type="text" class="form-control" placeholder="" autocomplete="off">
                        </div>
                     
                        <div class="col">
                            <label>Middle name</label>
                            <input name="middle_name" type="text" id="middle_name" class="form-control" placeholder="" autocomplete="off">
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col">
                            <label>Last name</label>
                            <input name="last_name" type="text" id="last_name" class="form-control" placeholder="" autocomplete="off">
                        </div>
                        <div class="col">
                            <label>Email</label>
                            <input name="email" type="email" id="email" class="form-control" placeholder="" autocomplete="off">
                        </div>
                        
                    </div>
                    <div class="row form-group">
                        <div class="col">
                            <label>Cellphone</label>
                            <input name="cellphone" type="number" id="cellphone" class="form-control" placeholder="" autocomplete="off">
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col">
                            <label>User Type</label>
                            <select name="user_type" class="form-control form2 selectpicker" data-style="btn btn-secondary">
                                <option value="0">Property Owner</option>
                                <option value="1">Admin</option>
                                <option value="2">Treasury</option>
                                <option value="3">Assessor</option>
                            </select>
                        </div>
                    </div>
                    <div class="row form-group text-right mt-3">
                        <div class="col">
                            <div class="form-message-container text-left">
                                <span class="form-message"></span>
                            </div>
                        </div>
                        <div class="col">
                            <button id="closeModal" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button id="addUserBtn" type="button" class="btn btn-primary right">
                                <span class="fa fa-spin fa-spinner mr-1 d-none"></span> Save Changes</button>
                        </div>
                    </div>
                </form>
            </div>

Add in your blade to every field:

<!-- ... -->
<div class="col">
    <label>First name</label>
    <div class="validation-message"></div>
    <input name="first_name" id="first_name" type="text" class="form-control" placeholder="" autocomplete="off">
</div>
<!-- ... -->

And to your js:

// ...
$.ajax({
        url: "/users-listing",
        data: payload,
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    }).done(function(res) {
        $("#addModal .fa-spinner").addClass('d-none');
        $("#addModal .form-message-container").html(res.message).addClass('text-success').fadeIn(1000);
        table.draw(false);
        setTimeout(() => {
            $("#addModal .form-message-container").html('').removeClass('text-success').fadeOut();
            $("#addModal [name=first_name]").val('');
            $("#addModal [name=middle_name]").val('');
            $("#addModal [name=last_name]").val('');
            $("#addModal [name=email]").val('');
            $("#addModal [name=cellphone]").val('');
            $("#addModal #closeModal").click();
        }, 3000);
    }).fail(function(err) {
        $("#addModal .fa-spinner").addClass('d-none');
        $("#addModal .form-message-container").html(err.responseJSON.message).addClass('text-danger').fadeIn(5000);
        setTimeout(() => {
            $("#addModal .form-message-container").html('').removeClass('text-danger').fadeOut();
        }, 5000);
        for (var [ el, message ] of Object.entries(err.responseJSON.errors)) {
            $('#' + el).addClass('is-invalid');
            $('#' + el).prev('.validation-message').text(message).addClass('is-invalid');
        }
    });
// ...

I was able to solve this by changing my route, and the error handling in AJAX. Thanks for all the inputs ideas here. :)

My fix: AJAX error code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM