Ad

Laravel Ajax Store Request Errormessage, Data Append To View

- 1 answer

I'm new to ajax and I have two little problems. With my code I can write the data in the database. I get no error messages and the data are not synonymous directly loaded into the view.

how can I load the data directly into the view without reload the page? if the privacy is 1, the code should be displayed in the right column, and if the privacy is 0, the code should be displayed in the left column.

How can I output the error messages with my errormessage code?

view

<div id="content" class="dashboard padding-10">
    <div class="row">
        <div class="col-md-offset-3 col-md-6">
            <a data-toggle="modal" data-target=".todolist-create-modal" class="btn btn-success btn-block btn-sm margin-bottom-10">Neue Liste erstellen</a>
        </div>
        <div class="col-md-6">
            <div id="panel-misc-portlet-l3" class="panel panel-default text-center">
                <div class="panel-heading nohover">
                    <span class="elipsis">
                        <strong>Private Tasks</strong>
                    </span>
                </div>
            </div>
            <div class="alert alert-danger margin-bottom-30 {{ $todolistpublic->count() ? 'hidden' : '' }}">
                Es wurden keine <strong>Einträge</strong> gefunden.
            </div>
            @foreach ($todolistpublic as $list)
                <div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
                    <div class="panel-heading panel-pointer">
                            <span class="elipsis"><!-- panel title -->
                                <strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
                            </span>
                        <ul class="options pull-right relative list-unstyled hover-visible">
                            <li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden">
                                    <i class="fa fa-plus"></i> Erstellen
                                </a>
                            </li>
                            <li><a data-toggle="modal" data-target=".todolist-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-info btn-xs white hover-hidden">
                                    <i class="fa fa-edit"></i> Bearbeiten
                                </a>
                            </li>
                            <li><a data-toggle="modal" data-target=".todolist-delete-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-danger btn-xs white hover-hidden">
                                    <i class="fa fa-times"></i> Löschen
                                </a>
                            </li>
                            <li><a target="_blank" rel="nofollow noreferrer" href="#" class="opt panel_colapse" data-placement="bottom"></a></li>
                        </ul>
                    </div>
                    <div class="panel-body">
                        <div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
                            {{ $list->description }}
                        </div>
                    </div>
                </div>
            @endforeach
            <div class="panel-footer mtm-10">
                <span id="todo-list-counter-public">{{ $todolistpublic->count() }}</span> <span>{{ $todolistpublic->count() > 1? 'Listen' : 'Liste' }}</span>
            </div>
        </div>

        <div class="col-md-6">
            <div id="panel-misc-portlet-l3" class="panel panel-default text-center">
                <div class="panel-heading nohover">
                    <span class="elipsis">
                        <strong>Öffentliche Tasks</strong>
                    </span>
                </div>
            </div>
            <div class="alert alert-danger margin-bottom-30 {{ $todolistprivate->count() ? 'hidden' : '' }}">
                Es wurden keine <strong>Einträge</strong> gefunden.
            </div>
            @foreach ($todolistprivate as $list)
                <div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
                    <div class="panel-heading panel-pointer">
                            <span class="elipsis"><!-- panel title -->
                                <strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
                            </span>
                        <ul class="options pull-right relative list-unstyled hover-visible">
                            <li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden"><i class="fa fa-plus"></i> Erstellen</a></li>
                            <li><a data-toggle="modal" data-target=".todolist-modal" class="btn btn-info btn-xs white hover-hidden"><i class="fa fa-edit"></i> Bearbeiten</a></li>
                            <li><a target="_blank" rel="nofollow noreferrer" href="#" class="btn btn-danger btn-xs white hover-hidden"><i class="fa fa-times"></i> Löschen</a></li>
                            <li><a target="_blank" rel="nofollow noreferrer" href="#" class="opt panel_colapse" data-placement="bottom"></a></li>
                        </ul>
                    </div>
                    <div class="panel-body">
                        <div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
                            {{ $list->description }}
                        </div>
                    </div>
                </div>
            @endforeach
            <div class="panel-footer mtm-10">
                <span id="todo-list-counter-private">{{ $todolistprivate->count() }}</span> <span>{{ $todolistprivate->count() > 1? 'Listen' : 'Liste' }}</span>
            </div>
        </div>

        @include('elements.addTodoList')
        @include('elements.createTodoList')
        @include('elements.addTask')
    </div>
</div>

$(document).ready(function () {
        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

        $('#add-todo-list').click(function(e) {
            e.preventDefault();
            var _token = $("input[name='_token']").val(); // get csrf field.
            var title = $("input[name='title']").val();
            var description = $("textarea[name='description']").val();
            var privacy = $("select[name='privacy']").val();
            $.ajax({
                url:'{{ route('todolists.store') }}',
                type: 'POST',
                data: {_token:_token, title:title, description:description, privacy:privacy},
                success: function (data) {
                    console.log(data);
                }
        });
        });
    });

Controller

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'required|min:5',
        'description' => 'required|min:10',
        'privacy' => 'required|integer'
    ]);

    $attributeNames = array(
        'title' => 'Title',
        'description' => 'Description',
    );
    $validator->setAttributeNames($attributeNames);
    //Redirect back if validation fails
    if($validator->fails()) {
        return response()->json(['error'=>$validator->errors()->all()]);
    }
    else{
        $todolists = new Todolists;
        $todolists->admin_id = auth::user();
        $todolists->title = $request->title;
        $todolists->description = $request->description;
        $todolists->privacy = $request->privacy;
        $todolists->save();
        return response()->json(['success'=>'Your enquiry has been successfully submitted!']);

    }

}

modal

<div class="modal fade todolist-create-modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Erstelle eine neue Liste</h4>
        </div>
        <div class="modal-body">
            <form action="{{ route('todolists.store') }}" method="post">
                {{ csrf_field() }}
                <div class="form-group">
                    <label for="" class="control-label">Titelname</label>
                    <div class="fancy-form">
                        <i class="fa fa-header"></i>
                        <input id="title" name="title" type="text" class="form-control input-lg" placeholder="Titel">
                    </div>
                </div>
                <div class="form-group">
                    <label for="" class="control-label">Beschreibung</label>
                    <div class="fancy-form">
                        <textarea id="description" name="description" rows="2" class="form-control" placeholder="Beschreibe deine Aufgabe"></textarea>

                        <i class="fa fa-comments"><!-- icon --></i>

                    </div>
                </div>
                <div class="form-group">
                    <label for="" class="control-label">Privatsphäre</label>
                    <div class="fancy-form fancy-form-select">
                        <select id="privacy" name="privacy" class="form-control">
                            <option selected value="0">Öffentlich</option>
                            <option value="1">Privat</option>
                        </select>
                        <i class="fancy-arrow"></i>
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-success" id="add-todo-list">Save changes</button>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

errormessages

 @if (count($errors) > 0)
    <div class="toastr-notify"></div>
            @foreach ($errors -> all() as $e)
                <script type="text/javascript">
                    _toastr("{{$e}}","top-right","error",false);
                </script>
            @endforeach
@endif

@if (session('fail'))
<div class="toastr-notify"></div>
    <script type="text/javascript">
        _toastr("{{ session('fail') }}","top-full-width","warning",false);
    </script>
@endif

@if (session('status'))
<div class="toastr-notify"></div>
    <script type="text/javascript">
        _toastr("{{ session('status') }}","top-full-width","info",false);
    </script>
@endif

@if (session('success'))
    <div class="btn btn-info toastr-notify"></div>
    <script type="text/javascript">
        _toastr("{{ session('success') }}","top-full-width","success", false);
    </script>
@endif

@if (session('error'))
    <div class="toastr-notify"></div>
    <script type="text/javascript">
        _toastr("{{ session('error') }}","top-full-width","error",false);
    </script>
@endif
Ad

Answer

I believe you have a typo in your ajax backend code; this line to be specific:

$todolists->admin_id = auth::user();

This should be:

$todolists->admin_id = auth()->user()->id;

The typo is generating a Throwable error, which is getting caught by the laravel exception handler and it's detecting that the code is being executed under a ajax request and hence returning a 500 internal server error.

Ad
source: stackoverflow.com
Ad