使用laravel 5.4返回json的验证

时间:2018-01-03 11:48:41

标签: php ajax laravel validation laravel-5.4

我有以下请求ajax:

$("#btnSave").click(function()
{ 
    var Url = 'http://localhost/Projetos-Laravel/Sibcomweb/public/panel/client/save';

    var Dados = $('#FormClient').serialize();

    $.ajax({
             type:'POST',
             url:Url,
             dataType: 'JSON',
             data: Dados,
             success:function(data){
                  if($.isEmptyObject(data.error)){
                     alert(data.msg);
                  }else{
                     alert('have errors');
                    }
                },
                error:function(e){
                  alert('Error !');
                  log.console(e);

                },
            });
        });

错误log.console(e)

POST http://localhost/Projetos-Laravel/Sibcomweb/public/panel/client/save 500 (Internal Server Error)
send @ jquery.js:9566
ajax @ jquery.js:9173
(anonymous) @ create:431
dispatch @ jquery.js:5206
elemData.handle @ jquery.js:5014
create:446 Uncaught ReferenceError: log is not defined
    at Object.error (create:446)
    at fire (jquery.js:3317)
    at Object.fireWith [as rejectWith] (jquery.js:3447)
    at done (jquery.js:9274)
    at XMLHttpRequest.<anonymous> (jquery.js:9514)

请求ajax转到控制器但在验证方法中有一些错误......

我认为问题出在验证方法中,我做错了吗?

public function store(Request $request)
{
    $dataForm = $request->all();

    $rules =[
    'name'=>'required|min:3|max:100',
    'number'=>'required|numeric',
    ];

    $valida = validator($dataForm, rules);
    if($valida->fails()) 
    {
        return $valida;
    }
    else
        return 'Ok';
}

如何在json中返回var valida?

3 个答案:

答案 0 :(得分:3)

日志不是功能。将log.console更改为console.log

答案 1 :(得分:0)

要查看回复错误:

将您的回调函数更改为:

  error: function(e){
    var errors = e.responseJSON;
    alert(errors);
    // Render the errors with js ...
  }

答案 2 :(得分:0)

有两个问题。 首先它是:log.console(e),但是是console.log(e)。 第二个问题是在控制器中,返回的方法不正确。

这是正确的:

public function store(Request $request)
{
    $dataForm = $request->all();

    $rules =[
    'name'=>'required|min:3|max:100',
    'number'=>'required|numeric',
    ];

    $valida = validator($dataForm, $rules);

    return response()->json(['error'=>$valida->errors()->all()]);
}