使用laravel验证后,对ajax的成功函数

时间:2016-06-12 19:17:10

标签: javascript jquery ajax laravel

我通过ajax用laravel验证了一个表单。正确地发送数据和验证工作,但是当收到js代码中的答案时,永远不会执行成功函数;如果验证错误中存在错误,则执行错误功能,如果验证功能中没有错误,也会输入错误。 出错时,它返回状态laravel:422,如果没有错误,则返回laravel status:200。

感谢您提供的帮助:)

JS:

function send(event){

    event.preventDefault();

    $.ajax({


        type: 'post',
        url: userAjax,
        dataType: 'json',
        data: {
            name: $('#name').val(),
            email: $('#email').val(),
            password: $('#password').val(),
            cpassword: $('#cpassword').val(),
            _token: $('#new-user').attr('data-token')
        },
        beforeSend: function()
        {
            $("#nameError").fadeOut();

        },
        success: function(errors){

            $('#Register').modal('hide');

        },
        error: function(errors) {


            console.log(errors);

        }

    });

}

laravel: UserController的:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Http\Requests\UserRequest;

class UserController extends Controller
{
    public function index()
    {
        return view('home');
    }
    public function NewUser(UserRequest $request)
    {
        // laravel will validate request itself automatically and
        // will go on if validate pass or will return back with
        // status code 422, input and errors otherwise

        CreateNewUser($request);

    }

    Protected function CreateNewUser(Request $request){

    }


}

UserRequest:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class UserRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
        public function rules()
    {
        return [
            'name' => 'required|max:255',
//            'email' => 'required|email|max:255|unique:users',
//            'password' => 'required|min:8|same:cpassword',
//            'cpassword'=> 'required|min:8',
        ];
    }

}

1 个答案:

答案 0 :(得分:0)

这是因为您的代码中存在错误。

CreateNewUser($request);

需要

$this->CreateNewUser($request);

Protected function CreateNewUser(Request $request){

需要:

protected function CreateNewUser(Request $request){