php 如何在laravel中使用 AJAX 验证输入数据

km0tfn4u  于 2022-12-10  发布在  PHP
关注(0)|答案(5)|浏览(154)

testAjax函数PostsController类中

public function testAjax(Request $request)
  {
    $name = $request->input('name');
    $validator = Validator::make($request->all(), ['name' => 'required']);

    if ($validator->fails()){
        $errors = $validator->errors();
        echo $errors;
    }
    else{
      echo "welcome ". $name;
    }

  }

web.php文件中:

Route::get('/home' , function(){
  return view('ajaxForm');
});

Route::post('/verifydata', 'PostsController@testAjax');

jaxForm.blade.php文件夹中的文件名:

<script src="{{ asset('public/js/jquery.js') }}"></script>

  <input type="hidden" id="token" value="{{ csrf_token() }}">
  Name<input type="text" name="name" id="name">
  <input type="button" id="submit" class="btn btn-info" value="Submit" />
<script>
  $(document).ready(function(){
      $("#submit").click(function(){
        var name = $("#name").val();
        var token = $("#token").val();
        /**Ajax code**/
        $.ajax({
        type: "post",
        url:"{{URL::to('/verifydata')}}",
        data:{name:name,  _token: token},
        success:function(data){
                //console.log(data);
                $('#success_message').fadeIn().html(data);
            }
          });
          /**Ajax code ends**/    
      });
  });
</script>

所以在点击提交按钮时通过输入一些数据然后输出提示信息(echo“welcome“. $name; )正在打印。但当我点击提交按钮与空文本框,然后它不打印错误消息从控制器,它抛出了一个422(不可处理的实体)错误在控制台。为什么我的方法是错误的,我如何打印错误消息,然后。请帮助。谢谢你提前。x1c 0d1xx 1c 1d 1x

iqjalb3h

iqjalb3h1#

你的方法实际上并没有错,只是你需要捕获 AJAX 请求的错误响应,而当Laravel验证失败时,它会抛出一个Error 422 (Unprocessable Entity)并显示相应的错误信息。

/**Ajax code**/
$.ajax({
    type: "post",
    url: "{{ url('/verifydata') }}",
    data: {name: name,  _token: token},
    dataType: 'json',              // let's set the expected response format
    success: function(data){
         //console.log(data);
         $('#success_message').fadeIn().html(data.message);
    },
    error: function (err) {
        if (err.status == 422) { // when status code is 422, it's a validation issue
            console.log(err.responseJSON);
            $('#success_message').fadeIn().html(err.responseJSON.message);
            
            // you can loop through the errors object and show it to the user
            console.warn(err.responseJSON.errors);
            // display errors on each form field
            $.each(err.responseJSON.errors, function (i, error) {
                var el = $(document).find('[name="'+i+'"]');
                el.after($('<span style="color: red;">'+error[0]+'</span>'));
            });
        }
    }
});
/**Ajax code ends**/

在控制器上

public function testAjax(Request $request)
{
    // this will automatically return a 422 error response when request is invalid
    $this->validate($request, ['name' => 'required']);

    // below is executed when request is valid
    $name = $request->name;

    return response()->json([
         'message' => "Welcome $name"
    ]);

  }
f1tvaqid

f1tvaqid2#

下面是一个更好的验证方法:
在控制器中:

public function testAjax(Request $request)
{
   $this->validate($request, [ 'name' => 'required' ]);
   return response("welcome ". $request->input('name'));
}

然后,框架将为您创建一个验证器并验证请求。如果验证失败,它将抛出一个ValidationException
假设您尚未覆盖验证异常的呈现方式,以下是内置异常处理程序将运行的默认代码

protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
        if ($e->response) {
            return $e->response;
        }
        $errors = $e->validator->errors()->getMessages();
        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }
        return redirect()->back()->withInput($request->input())->withErrors($errors);
}

同样,这是由框架为您处理的。
在客户端,您应该能够:

<script>
  $(document).ready(function(){
      $("#submit").click(function(){
        var name = $("#name").val();
        var token = $("#token").val();
        /**Ajax code**/
        $.ajax({
           type: "post",
           url:"{{URL::to('/verifydata')}}",
           data:{name:name,  _token: token},
           success:function(data){
              //console.log(data);
              $('#success_message').fadeIn().html(data);
           },
           error: function (xhr) {
               if (xhr.status == 422) {
                   var errors = JSON.parse(xhr.responseText);
                   if (errors.name) {
                       alert('Name is required'); // and so on
                   }
               }
           }
        });
          /**Ajax code ends**/    
      });
  });
</script>
ss2ws0br

ss2ws0br3#

在PHP控制器中处理的最佳方式:

$validator = \Validator::make($request->all(), [
        'footballername' => 'required',
        'club' => 'required',
        'country' => 'required',
    ]);
    
    if ($validator->fails())
    {
        return response()->json(['errors'=>$validator->errors()->all()]);
    }
    return response()->json(['success'=>'Record is successfully added']);
tvz2xvvm

tvz2xvvm4#

Vannilla Javascript中的表单验证代码

const form_data = new FormData(document.querySelector('#form_data'));
fetch("{{route('url')}}", {
       'method': 'post',
       body: form_data,
 }).then(async response => {
      if (response.ok) {
         window.location.reload();
      }
      const errors = await response.json();
      var html = '<ul>';
      for (let [key, error] of Object.entries(errors)) {
          for (e in error) {
              html += `<li>${error[e]}</li>`;
          }
      }
      html += '</ul>';
      //append html to some div

      throw new Error("error");
  })
  .catch((error) => {
     console.log(error)
  });

主计长

use Illuminate\Support\Facades\Validator;//Use at top of the page
$rules = [
    'file' => 'image|mimes:jpeg,png,jpg|max:1024',
    'field1' => 'required',
    'field2' => 'required'
   ];
$validator = Validator::make($request->post(), $rules);
if ($validator->fails()) {
   return response()->json($validator->errors(), 400);
}
session()->flash('flash', ['status' => 'status', 'message' => 'message']);
pbpqsu0x

pbpqsu0x5#

Jquery代码:

let first_name=     $('.first_name').val();
            let last_name=      $('.last_name').val();
            let email=     $('.email').val();
            let subject=      $('.subject').val();
            let message=        $('.message').val();

    $('.show-message').empty();

    console.log('clicked');
    $.ajax({
        type : 'POST',
        url  : '{{route("contact-submit")}}',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: {
            first_name,
            last_name,
            email,
            subject,
            message,
        },
        success: function(data) {

            console.log('data',data);
            $('.show-message').html('Form Submitted');
        },

        error :  function(data,data2,data3)
        {

            let response=data.responseJSON;
            let all_errors=response.errors;

            console.log('all_errors',all_errors);

            $.each(all_errors,function(key,value){
                $('.show-message').append(`<p>${value}</p>`);
            });

        }
    });

控制器代码:

$validator=Validator::make($request->all(),[
                'first_name'=>'required',
                'last_name'=>'required',
                'email'=>'required|email',
                'subject'=>'required',
                'message'=>'required',
            ]);

        if($validator->fails())
        {
            return response()->json([
                'success'=>false,
                'errors'=>($validator->getMessageBag()->toArray()),
            ],400);
        }

        return response()->json([
            'success'=>true,
        ],200);

如欲了解更多详细信息,请访问:https://impulsivecode.com/validate-input-data-using-ajax-in-laravel/

相关问题