7

Here is a part of my html file.

<div class="form-group{{ $errors->has('address_name') ? ' has-error' : '' }}">
    <label for="address_name">{{ trans('address.address_name') }} <span class="required_field">*</span></label>
    <input name="address_name" type="text" class="form-control" id="address_name" placeholder="{{ trans('address.address_name_placeholder') }}" maxlength="30">
    @if($errors->has('address_name'))
        <span class="help-block">{{ $errors->first('address_name') }}</span>
    @endif
</div>

I need to handle errors with Ajax Request in Laravel 5.1. Here is my code for handling

$validator = Validator::make($addressData, $this->rules());

    if ($validator->fails())
    {
        return response()->json([
            'success' => 'false',
            'errors'  => $validator->errors()->all(),
        ], 400);
    }
    else
    {
        //Save Address
        try
        {
            $this->insertAddress($addressData);
            return response()->json(['success' => true], 200);
        }
        catch(Exception $e)
        {
            return response()->json([
                'success' => 'false',
                'errors'  => $e->getMessage(),
            ], 400);
        }

    }

Console Message

{"success":"false","errors":["The Address Name field is required.","The Recipient field is required.","The Address field is required."]}

I can see errors in console but. In Blade i cannot reach $errors. How can i fix the problem ?

3 Answers 3

7

You are probably trying to work on different levels. Assuming that you are not handling the error response in your ajax script, there's no way for blade to know the error response, since the html page is provided by the controller as-is and it won't change until the next refresh. If you want to let blade know the response, you need to catch it asynchronously, that is ajax level.
Assuming again you are POSTing with a standard ajax request, you could do something like:

    var form = $('#your-form-id');
        $.ajax({
            url: form.attr( 'action' ),
            type: 'POST',
            data: form.serialize(),
            success: function(data){
                // Successful POST
                // do whatever you want
            },
            error: function(data){
                // Something went wrong
                // HERE you can handle asynchronously the response 

                // Log in the console
                var errors = data.responseJSON;
                console.log(errors);

                // or, what you are trying to achieve
                // render the response via js, pushing the error in your 
                // blade page
                 errorsHtml = '<div class="alert alert-danger"><ul>';

                 $.each( errors.error, function( key, value ) {
                      errorsHtml += '<li>'+ value[0] + '</li>'; //showing only the first error.
                 });
                 errorsHtml += '</ul></div>';

                 $( '#form-errors' ).html( errorsHtml ); //appending to a <div id="form-errors"></div> inside form  
                });
            }
        });  

Note that you will need a #form-errors div inside your posting form for this to work.

Sign up to request clarification or add additional context in comments.

3 Comments

'<li>'+ value[0] + '</li>'; why did you like that ? we need value[key] i think
@CihanKüsmez yea, key if you got more than one error. I did specify that it shows only one error and I believe that's up to your very needs.
$.each( data, function( key, value ) { should be $.each( errors.errors, function( key, value ) {
3

Hope that will help you

        $.ajax({
            url: form.attr( 'action' ),
            type: 'POST',
            data: form.serialize(),
            success: function(data){
                // do whatever you want
            },
            error: function(data){

                // Log in the console
                var errors = data.responseJSON;
                console.log(errors);

                // or, what you are trying to achieve
                // render the response via js, pushing the error in your 
                // blade page

                    var errors = response.responseJSON;
                   errorsHtml = '<div class="alert alert-danger"><ul>';
                  $.each(errors.errors,function (k,v) {
                         errorsHtml += '<li>'+ v + '</li>';
                  });
                  errorsHtml += '</ul></di>';

                  $( '#error_message' ).html( errorsHtml );

                   //appending to a <div id="error_message"></div> inside your form  
                });
            }
        }); 

Comments

0

Here is more concise solution. Happy hacking :)

   .fail((err) => {     
    let allErrors = Object.values(err.responseJSON)
    .map(el => (
      el = `<li>${el}</li>`
    ))
    .reduce((next, prev) => ( next = prev + next ));   
    const setErrors = `
      <div class="alert alert-danger" role="alert">
          <ul>${allErrors}</ul>
      </div>
    `;
    $('.modalErrorr').html(setErrors);

  })       
  .always((data) => {
    
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.