500内部服务器错误,而发布数据与laravel 5和ajax数据库


500 internal server error while posting data to database with laravel 5 and ajax

大家好!我试图使用laravel 5和ajax发布数据到数据库..我也通过添加

应用使用CSRF保护

<meta name="_token" content="{!! csrf_token() !!}"/>

到我的布局页眉,并添加以下代码到我的页脚:

<script type="text/javascript">
$.ajaxSetup({
   headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>

这是我的表单:

<form action="{{action('QuizController@postQuiz')}}" method="POST">
<div id="name-group" class="form-group">
<label for="name">Please type your question here</label>
<input type="text" class="form-control" name="question">
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
这是我的JS代码:
var formData = {
'question'    : $('input[name=question]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'quiz',
data : formData, 
dataType : 'json', 
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console to see
console.log(data); 

// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();

这是我的路线:

Route::post('create/quiz', array(
'as' => 'post-quiz',
'uses' => 'QuizController@postQuiz'
));

当我的控制器如下所示:

public function postQuiz()
{
if(Request::ajax()) {
$question = Request::get('question');
$data['success'] = true;
$data['message'] = $question;
echo json_encode($data);
   }

ajax调用工作并返回,

Object {success: true, message: "test question"}

,但当我尝试发送数据到数据库使用:

public function postQuiz()
{
if(Request::ajax()) {
$question = Request::get('question');
DB::table('questions')->insert([
'question' => $question,
]);
     }

我从控制台

得到以下内容
POST http://localhost/leoschool-laravel5/public/create/quiz 500 (Internal Server Error)

Object {readyState: 4, responseText: "{"success":true,"message":"test question"}<!DOCTYPE htm…l>↵</div>↵↵            </div>↵    </body>↵</html>", status: 500, statusText: "Internal Server Error"}

有什么问题吗?谢谢. .

Chrome Developer工具是一个很好的开始。打开工具加载页面,并触发执行AJAX请求的事件。

在工具的network选项卡下,它将显示所发出的每个请求,并允许您预览响应,就好像您没有使用AJAX一样。这将显示laravel堆栈跟踪。我认为问题是你在使用facade,它们没有正确地命名空间。

改变你的控制器功能,看看它是否工作:

public function postQuiz()
{
    if('Request::ajax()) {
        $question = 'Request::get('question');
        'DB::table('questions')->insert([
            'question' => $question,
        ]);
}
有了上面关于如何使用开发工具的说明和正确的代码,你应该能够解决你的问题。写这段代码的更好的方法是这样的:
// assuming you have these models setup
// this uses dependency injection
public function postQuiz(Request $request, Question $question)
{
    if($request->ajax()) {
        $newQuestion = $request->get('question');
        //add fields here to create new question with
        $question->create([ /*stuff*/ ]);
}