在模态ajax中显示错误

时间:2017-02-09 08:54:35

标签: ajax laravel

我是ajax的新手,我想在我的模态中显示错误。我正在使用laravel

这是我的刀片

>附加store.blade.php

<div class="pull-right">
    <button class="btn btn-success btn-outline" data-toggle="modal" data-target="#addBtn">+Add a new Store</button>
    <div id="addBtn" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h5 class="modal-title" id="myModalLabel">Add A New Store</h5>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-group">
                            <label class="control-label mb-10">Full Name</label>
                            <input type="text" class="form-control" name="name" id="name" placeholder="John Doe">
                        </div>

                        <div class="form-group">
                            <label class="control-label mb-10">Email</label>
                            <input type="email" class="form-control" name="email" id="email" placeholder="">
                            <p class="error text-center alert alert-danger hidden">
                        </div>

                        <div class="form-group">
                            <label class="control-label mb-10">Password</label>
                            <input type="password" class="form-control" name="password" id="password" placeholder="">
                        </div>

                        <div class="form-group">
                            <label class="control-label mb-10">Designate Store</label>
                            <select class="form-control" name="store_id" id="store_id">
                            </select>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success waves-effect" data-dismiss="modal" id="save">Save</button>
                    <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Cancel</button>
                </div>

            </div>
            <!-- /.modal-content -->
        </div>
    </div>
</div>

我在页面末尾的脚本

<script>
    var urlAdd = '{{ route('addSocialWorker') }}';
    var token = '{{ Session::token() }}';

    $("#save").click(function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: urlAdd,
            data: {
                'name': $('#name').val(),
                'email': $('#email').val(),
                'password': $('#password').val(),
                'store_id': $("#store_id").val(),
                '_token': token
            },
            success: function (data) {
                if ((data.errors)) {
                    console.log(data);
                } else {
                    $('#usersTable').append(data);
                }
            },
        });
    });
</script>

AdminController.php

public function addSocialWorker(Request $request)
{
    $rules = [
        'name'     => 'required|max:255',
        'email'    => 'required|email|unique:users',
        'password' => 'required|min:4',
        'store_id' => 'required|numeric',
    ];

    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails()) {
        return Response::json([
            'errors' => $validator->getMessageBag()->toArray(),
        ]);
    } else {
        $data = new User();
        $data->name = $request->name;
        $data->email = $request->email;
        $data->password = $request->password;
        $data->status = 1;
        $data->role_id = 2;
        $data->store_id = $request->store_id;
        $data->save();

        return response()->json($data);
    }
}

以上验证。我是ajax和jquery的新手。您是否有想法如何在模态中显示错误?

2 个答案:

答案 0 :(得分:0)

首先,您需要在模态体中创建类 - 让它调用它的错误,并将它放在模态体的最底部。这就是你的错误所在的地方。

<div class="errors"></div>

如果数据从控制器正确发送,则需要循环每个错误(在您的成功功能中)。 (alert alert-danger类是bootstrap类,你可以删除它)

for (var i in data) {

  $('errors').append('<div class="alert alert-danger">'+data[i].error_text+'</div>');

}

error_text可以是多才多艺的,它取决于您的数据响应中返回的内容。您可以使用 console.log(数据)来查看。

答案 1 :(得分:0)

首先,您可以清理控制器:

public function addSocialWorker(Request $request)
{
    $this->validate($request, [
        'name'     => 'required|max:255',
        'email'    => 'required|email|unique:users',
        'password' => 'required|min:4',
        'store_id' => 'required|numeric',
    ]);

    $data = new User();
    $data->name = $request->name;
    $data->email = $request->email;
    $data->password = $request->password;
    $data->status = 1;
    $data->role_id = 2;
    $data->store_id = $request->store_id;

    return response()->json($data);
}

通过上述内容,您不必手动检查验证是否通过,它还将发送具有正确HTTP状态的响应(422)。

您需要在ajax调用中添加error方法,以便实际捕获错误,因为错误时不会调用success

success: function (data) {
   $('#usersTable').append(data);
},
error: function (res) {

    if (res.status == 422) {
        var data = res.responseJSON;

        for (let i in data) {
            console.log(i, data[i][0])
        }
    }
}

然后,如果你想显示错误,你可以这样:

<form>
    <div class="form-group" id="form-group-name">
        <label class="control-label mb-10">Full Name</label>
        <input type="text" class="form-control" name="name" id="name" placeholder="John Doe">
        <span class="help-block"></span>
    </div>

    <div class="form-group" id="form-group-email">
        <label class="control-label mb-10">Email</label>
        <input type="email" class="form-control" name="email" id="email" placeholder="">
        <span class="help-block"></span>
        <p class="error text-center alert alert-danger hidden">
    </div>

    <div class="form-group" id="form-group-password">
        <label class="control-label mb-10">Password</label>
        <input type="password" class="form-control" name="password" id="password"
               placeholder="">
        <span class="help-block"></span>
    </div>

    <div class="form-group" id="form-group-store_id">
        <label class="control-label mb-10">Designate Store</label>
        <select class="form-control" name="store_id" id="store_id">
            <option value="1">One</option>
            <option value="2">Two</option>
        </select>
        <span class="help-block"></span>
    </div>

</form>

//

<script>
    $(document).ready(function () {

        function showValidationErrors(name, error) {

            var group = $("#form-group-" + name);
            group.addClass('has-error');
            group.find('.help-block').text(error);
        }

        function clearValidationError(name) {
            var group = $("#form-group-" + name);
            group.removeClass('has-error');
            group.find('.help-block').text('');
        }

        $("#name, #email, #password").on('keyup', function () {
            clearValidationError($(this).attr('id').replace('#', ''))
        });
        $("#store_id").on('change', function () {
            clearValidationError($(this).attr('id').replace('#', ''))
        });

        $("#save").click(function (e) {
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: '{{ route('addSocialWorker') }}',
                data: {
                    'name': $('#name').val(),
                    'email': $('#email').val(),
                    'password': $('#password').val(),
                    'store_id': $("#store_id").val(),
                    '_token': '{{ Session::token() }}'
                },
                success: function (data) {
                    console.log(data, 'I am the success method')
                },
                error: function (res) {

                    if (res.status == 422) {
                        var data = res.responseJSON;

                        for (let i in data) {
                            showValidationErrors(i, data[i][0])
                        }
                    }
                }
            });
        });
    });
</script>

希望这有帮助!