Blues Clues
Blues Clues

Reputation: 1838

How to handle validation errors in laravel5.1 using ajax/jquery

Im creating a validation now using laravel5.1 with ajax of jquery. Everything works fine. But, what I want is to display the errors each <inputs> just like when using validation without ajax. Please see my code below, and the picture for the sample output. I've also tried it with @if of blade(laravel), but not working.

Note: Im using bootstrap framework too.

<div class="row">
  <div class="col-md-6">
    <div id="result">
        <ul></ul>
        </div>
        <form action="" method="post" id="create">
            <div class="form-group">
                <label for="name" class="control-label">Name</label>
                <input type="text" name="name" id="name" class="form-control">
            </div>

            <div class="form-group">
                <label for="description" class="control-label">Description</label>
                <textarea name="description" id="description" cols="30" rows="10" class="form-control"></textarea>
            </div>

            <div class="form-group">
                <label for="type" class="control-label">Type</label>
                <input type="text" name="type" id="type" class="form-control">
            </div>

            <div class="form-group">
                <label for="price" class="control-label">Price</label>
                <input type="text" name="price" id="price" class="form-control">
            </div>

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-success">
            </div>

            {{ csrf_field() }}
        </form>
    </div>
</div>


<script>
    $(document).ready(function(){
        var url = '{{ route('ajax-push') }}';
        var token = '{{ csrf_token() }}';
        $('#create').on('submit', function(){
            $.ajax({
                type: 'POST',
                url: url,
                data: { _token: token },
                dataType: 'json',
                success: function(data){
                    console.log(data);
                },
                error: function(data){
                    var errors = data.responseJSON;
                    $('#result').removeClass('alert').removeClass('alert-danger');
                    $('#result > ul').empty();
                    $.each(errors, function(i, item){
                        $('#result').addClass('alert').addClass('alert-danger');
                        $('#result > ul').append('<li>' + item + '</li>');
                    });
                }
            });

            return false;
        });
    });
</script>

Controller

public function postAjaxCreate(Request $request){
        $validator = $this->validate($request, [
            'name' => 'required|max:255',
            'description' => 'required|min:2',
            'type' => 'required|max:255',
            'price' => 'required|numeric'
        ]);

        if($validator->fails()){
            return response()->json($validator->messages(), 200)->with($validator->messages());
        }
    }

enter image description here

Upvotes: 0

Views: 32

Answers (1)

madalinivascu
madalinivascu

Reputation: 32354

You need to pass the from data to the ajax request

data: $('#create').serialize(),

and most likely the response doesn't have a responseJSON property, and you are sending the data twice from, remove the with function in you php function

Add the errors to the page using something similar to the following js:

$.each(data, function(i, item){
  $('#'+i).addClass('alert alert-danger'); 
  ('#'+i).after('<p>' + item + '</p>');
});

Upvotes: 1

Related Questions