When I ajax accessed to server, I got 422 (Unprocessable Entity) error.
Does anyone know how to fix it?
<meta name="csrf-token" content="{{ csrf_token() }}" />
<script>
$(document).ready(function(){
$("#frm").submit(function(e){
e.preventDefault();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'post',
url : 'http://example.com/contact',
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
});
</script>
I got this error.
http://example.com/contact 422 (Unprocessable Entity)
I checked form data by Google Chrome. It seems to be OK..
_token:nBfBpE56cFqgmEy94KCji975dZXt3K5MSnlHJT5y
Update
I added 'address' parameter which was required parameter by following ConvertToInt32's commnet. And then I got another error which was HTTP 403 (Forbidden) error.
<script>
$(document).ready(function(){
$("#frm").submit(function(e){
e.preventDefault();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var address = $("textarea#address").val();
$.ajax({
type: 'post',
url : 'http://example.com/contact',
data: {'_token': CSRF_TOKEN, 'address' : address},
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
});
</script>
Update
app\Http\Requests
<?php namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest {
public function authorize()
{
// Honeypot
return $this->input('address') == '';
}
}
ContactRequest
?php namespace App\Http\Requests;
class ContactRequest extends Request {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'message' => 'required'
];
}
}
Request parameter may be OK.
_token:nBfBpE56cFqgmEy9wKCjixf5dZXt3K4MSnlHJT3y
address:a
422 is natural response code in laravel for invalid data when submitting forms via ajax.And your data must include all fields that is defined in your request rules method. 403 means you are not authorized to perform that request.In your request class there is method called
authorize()
.And you can use this method to check if user has an authority to make this request.If this return false then you will get 403 error.