Laravel ajax 422(不可处理的实体)

时间:2017-09-02 15:09:17

标签: php jquery ajax laravel

我在laravel中有一个注册表单,该表单在没有ajax的情况下正常运行。但我想使用Ajax发布数据。我写了Ajax代码发布但我在控制台中收到错误消息,即422 (unprocessable Entity)

  

registration.blade.php

@extends('layouts.layout')

@section('content')
    <div class="container">
        <div class="row">
            <div style="width:100%; max-width: 500px; margin: auto;">
                <h3 class="text-center"><u>Register with us</u></h3>
                <hr>
                <form id="registrationForm" method="post" action="/submitRegistrationData" enctype="multipart/form-data">
                    {{ csrf_field() }}
                    <div class="form-group">
                        <label>First name: <span><em>{{$errors->first('fname')}}</em></span></label>
                        <input type="text" class="form-control" id="fname" name="fname" value="{{ old('fname') }}">
                    </div>
                    <div class="form-group">
                        <label>Last name: <span><em>{{$errors->first('lname')}}</em></span></label>
                        <input type="text" class="form-control" id="lname" name="lname" value="{{ old('lname') }}">
                    </div>
                    <div class="form-group">
                        <label>Phone: <span><em>{{$errors->first('phone')}}</em></span></label>
                        <input type="text" class="form-control" id="phone" name="phone" maxlength="10" value="{{ old('phone') }}">
                    </div>
                    <div class="form-group">
                        <label>Email address: <span><em>{{$errors->first('email')}}</em></span></label>
                        <input type="text" class="form-control" id="email" name="email" value="{{ old('email') }}">
                    </div>
                    <div class="form-group">
                        <label>DOB: <span><em>{{$errors->first('dob')}}</em></span></label>
                        <input type="date" class="form-control" id="dob" name="dob" value="{{ old('dob') }}">
                    </div>
                    <div class="form-group">
                        <label>Gender: <span><em>{{$errors->first('gender')}}</em></span></label>
                        <input type="radio" name="gender" value="M" @if(old('gender') == 'M') checked @endif> Male
                        <input type="radio" name="gender" value="F" @if(old('gender') == 'F') checked @endif> Female
                    </div>
                    <div class="form-group">
                        <label>City: <span><em>{{$errors->first('city')}}</em></span></label>
                        <select class="form-control" name="city">
                            <option value="">Select</option>
                            <option value="Guwahati" {{ (old('city') == 'Guwahati') ? 'selected' : '' }}>Guwahati</option>
                            <option value="Kolkata" {{ (old('city') == 'Kolkata') ? 'selected' : '' }}>Kolkata</option>
                            <option value="Delhi" {{ (old('city') == 'Delhi') ? 'selected' : '' }}>Delhi</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Hobbies: <span><em>{{$errors->first('hobbies')}}</em></span></label>
                        <input type="checkbox" name="hobbies[]" value="Cricket" {{ !empty(old('hobbies')) && (in_array('Cricket', old('hobbies'))) ? 'checked' : ''}}> Cricket
                        <input type="checkbox" name="hobbies[]" value="Football" {{ !empty(old('hobbies')) && (in_array('Football', old('hobbies'))) ? 'checked' : ''}}> Football
                        <input type="checkbox" name="hobbies[]" value="Badminton" {{ !empty(old('hobbies')) && (in_array('Badminton', old('hobbies'))) ? 'checked' : ''}}> Badminton
                    </div>
                    <div class="form-group">
                        <label>Photo: <span><em>{{$errors->first('profile_photo')}}</em></span></label>
                        <input type="file" class="form-control" id="profile_photo" name="profile_photo" value="{{ old('profile_pic') }}">
                    </div>
                    <div class="form-group">
                        <label>Password: <span><em>{{$errors->first('password')}}</em></span></label>
                        <input type="password" class="form-control" id="password" name="password" value="">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>    
@endsection

@section('script')
    <script type="text/javascript" src="{{ URL::asset('js/registration.js') }}"></script>
@endsection
  

UserController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests\ValidateRegistration;

use Illuminate\Support\Facades\Hash;

use Illuminate\Http\Request;

use App\User;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $title = "Registration";
        return view('/registration', compact('title'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ValidateRegistration $request)
    {
        //dd(request()->all());
        if( !isset($errors) )
        {
            $path = $request->file('profile_photo')->store('uploads');
            $hobbies = '';
            foreach( request('hobbies') as $hobby )
            {
                $hobbies .= $hobby.',';
            }
            $password = Hash::make(request('password'));
            $activationKey = Hash::make(rand());
        }

        User::create([
            'fname'         => request('fname'),
            'lname'         => request('lname'),
            'phone'         => request('phone'),
            'email'         => request('email'),
            'gender'        => request('gender'),
            'city'          => request('city'),
            'hobbies'       => $hobbies,
            'password'      => $password,
            'profile_pic'   => $path,
            'activationKey' => $activationKey
        ]);

        // redirect to home page
        return redirect('/registration-success');

        $data = array();
        $data['status'] = 'success';
        $data['message'] = 'Registration success';
        return response()->json($data);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
  

ValidateRegistration.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ValidateRegistration extends FormRequest
{
    /**
     * 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 [
            'fname'         => 'required',
            'lname'         => 'required',
            'phone'         => 'required|size:10|regex:/^[0-9]+$/i|unique:users,phone',
            'email'         => 'required|regex:/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/|unique:users,email',
            'gender'        => 'required',
            'profile_photo' => 'required|image',
            'password'      => 'required'
        ];
    }

    /**
    * Get the error messages for the defined validation rules.
    *
    * @return array
    */
    public function messages()
    {
        return [
            'fname.required' => 'Firstname is mandatoy',
            'lname.required'  => 'Lastname is mandatory',
            'phone.required'  => 'Phone is mandatory',
            'phone.size'  => 'Phone must be 10 digit',
            'phone.unique'  => 'Phone number already exist',
            'phone.regex'   => 'Invalid phone',
            'email.required'  => 'Email is mandatory',
            'email.unique'  => 'Email already exist',
            'email.regwx' => 'Invalid email',
            'gender.required'   => 'Please select gender',
            'profile_photo.required'  => 'Profile pic is mandatory',
            'profile_photo.image'     => 'Invalid image',
            'password.required'  => 'Password is mandatory',
        ];
    }
}
  

registration.js

$(document).ready(function(){
    $('#registrationForm').submit(function(e){
        e.preventDefault();

        formInputs = $('#registrationForm').serialize();
        console.log(formInputs);
        $.ajaxSetup({
            url: "/submitRegistrationData",
            data: formInputs,
            async: true,
            dataType: 'json',
            beforeSend: function () {
            },
            complete: function(){
            }
        });
        $.post()
        .done(function(response) {
            console.log(response);
        })
        .fail(function() {
            console.log('failed');
        })
    });
});

4 个答案:

答案 0 :(得分:1)

这是典型的验证错误。只需检查浏览器devtools你通过ajax发送什么,我想你很容易找到一个缺少的解决方案。

使用网络标签,选择XHR并找到您的请求。查看标题标签的底部,这里应该是您的数据 - http://joxi.ru/V2VLXKvhxQpN4r

答案 1 :(得分:0)

您可能需要添加此内容。

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

答案 2 :(得分:0)

此错误是因为服务器端无法识别您的数据。

您可以尝试使用以下javascript:

function formDataToJSON(form) {
    let obj = {};
    let formData = form.serialize();
    let formArray = formData.split("&");

    for (inputData of formArray){
        let dataTmp = inputData.split('=');
        obj[dataTmp[0]] = dataTmp[1];
    }
    return JSON.stringify(obj);
}

$(document).ready(function(){
    $('#registrationForm').submit(function(e){
        e.preventDefault();

        let form = $(this);
        let formData = formDataToJSON(form);

        $.ajax({
            type: "POST",
            url: "/submitRegistrationData",
            data: formData, // serializes the form's elements.
            headers : {
                "content-type": "application/json",
                "accept": "application/json",
            },
            success: function(data){
                console.log(data); // show response from the php script.
            },
            error : function(response, textStatus, errorThrown){
                console.log(errorThrown);   
            }
        }); 

    });
});

答案 3 :(得分:0)

我有类似的问题。我一直在发送GET请求到POST路由。