每次尝试发出Ajax请求时,我都会收到500内部错误。根据调试,500错误不会弹出,直到" if"商店功能中的声明。我不能为我的生活找出原因。当我通过常规发布请求运行代码并丢弃Ajax时,它工作正常。有什么想法吗?:
public function store( Request $request, $project_id ) {
//current logged in user.
$user_id = auth()->user()->id;
//get all post inputs
$inputs = $request->all();
//make sure project ID belongs to current user. Stop someone from adding a task to your project that isn't you.
$projectBelongsToUser = Project::find(1)->where('user_id', $user_id)->where('id', $project_id);
//if a project ID and inputs are provided - log them to the database, if not redirect to home with $errors.
if( $project_id && $inputs['submit'] && $projectBelongsToUser ) {
$task = New Task;
$task->description = $inputs['description'];
$task->due_date = $inputs['due_date'];
$task->priority = $inputs['priority'];
$task->completed = 0;
$task->order = 0;
$task->user_id = $user_id;
$task->project_id = $project_id;
$task->save();
//get all tasks
$tasks = Task::all();
//sanitize tasks for safe output
function sanitize_object_h( $array ) {
$array_modified = $array;
foreach( $array_modified as $object ) {
foreach( $object as &$item ) {
$item = htmlentities( $item, ENT_QUOTES );
}
//end foreach
}
//end foreach
return $array_modified;
}
//end sanitize_object_h
$sanitized_tasks = sanitize_object_h( $tasks );
//return the sanitized object.
echo json_encode( $sanitized_tasks );
// return redirect( '/tasks/' . $project_id );
} else {
echo "failed";
return;
}//end if
}//end store
JavaScript的:
function postData( form, url ) {
var returnData;
console.log("form data " + form.serialize());
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type:"POST",
data: form.serialize(),
success:function(data){
console.log(data);
},error:function(data){
console.log(data);
}
}); //end of ajax
return returnData;
}//end postData
头脑中的HTML:
<meta name="csrf-token" content="{{ csrf_token() }}">