简体   繁体   English

Laravel Ajax 响应和错误处理

[英]Laravel Ajax Response And Handling Errors

Here is a part of my html file.这是我的 html 文件的一部分。

<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.我需要处理 Laravel 5.1 中的 Ajax 请求错误。 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.在 Blade 中,我无法达到 $errors。 How can i fix the problem ?我该如何解决这个问题?

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.假设您没有在 ajax 脚本中处理错误响应,刀片无法知道错误响应,因为 html 页面是由控制器按原样提供的,并且在下一次刷新之前不会更改。 If you want to let blade know the response, you need to catch it asynchronously, that is ajax level.如果想让刀片知道响应,则需要异步捕获它,即ajax级别。
Assuming again you are POSTing with a standard ajax request, you could do something like:再次假设您使用标准 ajax 请求进行 POST,您可以执行以下操作:

    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.请注意,您需要在发布表单中使用#form-errors div 才能使其工作。

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

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) => {
    
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM