skip to Main Content

I have a basic form that collects user information (name, surname, etc)

An example of one input field:

<div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" name="name" value="{{ old('name', $user->name) }}">
    @if ($errors->has('name'))
        <span class="help-block">
            <strong>{{ $errors->first('name') }}</strong>
        </span>
    @endif
</div>

I send this data via an AJAX request to the server. If errors occur during validation then I want to return a view with the errors showing.
Something like this:

$html = view('partials.update_form')->withErrors($validator)->withInput()->render();
return response()->json(['html' => $html, 'status' => 'error']);

However, this returns error 500
I have also tried making sure that the user’s data is added like so:

$html = view('partials.update_form', compact('user'))->withErrors($validator)->withInput()->render();
return response()->json(['html' => $html, 'status' => 'error']);

This also proved to be fruitless
Any help would be greatly appreciated

Here is my AJAX request just to give you a full picture:

var formData = new FormData($('#update-user-form')[0]);
if ($('form').find('input[name=avatar]').val() != '') {
        formData.append('avatar', $('form').find('input[name=avatar]')[0].files[0], $('form').find('input[name=avatar]').val());
    }
    var id = $('form').find('input[name=id]').val();
    $.ajax({
        type: "POST",
        dataType: "json",
        enctype: 'multipart/form-data',
        url: 'admin/edit/'+id,
        data: formData,
        processData: false,
        contentType: false,
        success: function (response) {  
            console.log(response);
            $('.update-form-wrapper').html(response.html);

        }
    });

Here is the appended Logs for those that asked:

Call to undefined method IlluminateSupportMessageBag::getBag() (View: /var/www/emailix/resources/views/partials/update_form.blade.php) {"userId":1,"exception":"[object] (Facade\Ignition\Exceptions\ViewException(code: 0): Call to undefined method Illuminate\Support\MessageBag::getBag() (View: /var/www/emailix/resources/views/partials/update_form.blade.php) at /var/www/emailix/resources/views/partials/update_form.blade.php:21)
[stacktrace]

I hope that provides some more clearity

2

Answers


  1. Chosen as BEST ANSWER

    So I spent a while trying to figure this whole thing out. I guess that the render() directive does not handle withError() and withInput(). What I decided to do was just pass the validation errors to the view under an "Alias" if you will so that it bypasses the messageBag.

    $formErrors =  $validator->errors();
    $html = View::make('partials.update_form', compact(['user', 'formErrors']))->render();
    return response()->jsons(['html' => $html]);
    

    This solved the problem, but I had to handle the blade a bit differently compared to the shorthand methods that are available if you are using the standard $error variable. Here is an example of what my blade looks like now:

    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control {{ (isset($formErrors) && $formErrors->has('name')) ? 'is-invalid' : ''}}" id="name" name="name" value="{{ old('name', $user->name) }}">
        @if (isset($formErrors) && $formErrors->has('name'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $formErrors->first('name') }}</strong>
            </span>
        @endif
    </div>
    

    I guess I answered my own question for now, but I am still open to suggestions for other workarounds


  2. The best way to solve this problem “X-CSRF-TOKEN” is to add the following code to your main layout, and continue making your ajax calls normally:

    in header

    <meta name="csrf-token" content="{{ csrf_token() }}" />
    

    and add javascript code

    <script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    </script>
    

    Referrer : https://stackoverflow.com/a/41867849/12520848

    Also: please share the error log if you have any other problems.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search