我正在使用Ajax在Laravel中进行表单提交,但挂起了,检查console.log我收到内部服务器错误500
我正在使用Laravel 5.8,使用console.log在meta名称和ajax函数中都包含了csrf令牌,包括_token在内的所有值都出现在控制台中
这是表格控制器
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator,Redirect,Response;
use App\Contact;
class FormController extends Controller
{
public function index()
{
return view('ajax-form');
}
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'mobile_number' => 'required|unique:users'
]);
$data = $request->all();
$check = Contact::insert($data);
$arr = array('msg' => 'Something goes to wrong. Please try again lator', 'status' => false);
if($check){
$arr = array('msg' => 'Successfully submit form using ajax', 'status' => true);
}
return Response()->json($arr);
}
}
这是我的刀片文件
Laravel 5.7.error{ color:red; }
Laravel 5.7 Ajax Form Submission Example - TutsMake
{{--
--}}@csrf
Name
{{ $errors->first('name') }}
Email Id
{{ $errors->first('email') }}
Mobile Number
{{ $errors->first('mobile_number') }}
Submit
if ($("#contact_us").length > 0) {
$("#contact_us").validate({
rules: {
name: {
required: true,
maxlength: 50
},
mobile_number: {
required: true,
digits:true,
minlength: 10,
maxlength:12,
},
email: {
required: true,
maxlength: 50,
email: true,
},
},
messages: {
name: {
required: "Please enter name",
maxlength: "Your last name maxlength should be 50 characters long."
},
mobile_number: {
required: "Please enter contact number",
minlength: "The contact number should be 10 digits",
digits: "Please enter only numbers",
maxlength: "The contact number should be 12 digits",
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},
},
submitHandler: function(form) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#send_form').html('Sending..');
console.log($('#contact_us').serialize());
$.ajax({
url: "{{ url('save-form')}}",
type: "POST",
data: $('#contact_us').serialize(),
success: function( response ) {
$('#send_form').html('Submit');
$('#res_message').show();
$('#res_message').html(response.msg);
$('#msg_div').removeClass('d-none');
document.getElementById("contact_us").reset();
setTimeout(function(){
$('#res_message').hide();
$('#msg_div').hide();
},1000);
}
});
}
})
}
我的路线
Route::post('save-form', 'FormController@store');
我需要将表单提交到数据库。