Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138221

Laravel: Render a view with errors and input that can be returned to AJAX

$
0
0

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);

        }
    });

Viewing all articles
Browse latest Browse all 138221

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>