查询数据库时AJAX jQuery不起作用

时间:2018-12-01 06:49:25

标签: javascript php jquery ajax laravel-5.2

在我的代码中,我从用户那里获得了first_namelast_nameemailpassword。然后,在第二页中得到我/她的同意后,我将获得用户的位置。因此,我将第一页的所有信息另存为session变量。然后,我有一个看起来像这样的按钮:

<button onclick="signUp()" class="btn btn-primary"> Let's go! </button>

signUp函数如下所示:

function signUp(){

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


        $.post("/sign-up-user",
        {
            user_latitude: latitude,
            user_longitude: longitude
        }, function(data){
            alert(data);
        });
    }

而且,我的请求路线为:

Route::post("/sign-up-user", "PagesController@signUpFinalUser");

而且,我的PagesController函数signUpFinalUser看起来像这样:

// Finally acquire the user with location and store him/her in the database
public function signUpFinalUser(Request $request){
  // Get all required variables
  $final_first_name = Session::get("user_first_name");
  $final_last_name = Session::get("user_last_name");
  $final_email = Session::get("user_email");
  $final_password = Session::get("user_password");
  $final_latitude = (float) $request->user_latitude;
  $final_longitude = (float) $request->user_longitude;

  // Create a new instance of the User model
  $user = new User;
  // Fill all the required columns of the database of the user
  $user->first_name = $final_first_name;
  $user->last_name = $final_last_name;
  $user->email = $final_email;
  $user->password = $final_password;
  $user->latitude = $final_latitude;
  $user->longitude = $final_longitude;
  // Save the user i.e store the user in the database
  $user->save();
  // Get the id of the user
  $user_id = $user->id;
  // Destroy all the sessions variable
  Session::destroy();
  // Create a session variable named 'user_id'
  Session::put("user_id", $user_id);
  // Return a response back
  return 1;
}

但是,问题是,它显示了如下所示的错误:

jquery.min.js:2 POST http://localhost:8000/sign-up-user 500 (Internal Server Error)

但是,令人惊讶的是,当我注释掉数据库查询并再次运行它时,响应数据即“ 1”被警告。那么,我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您在放置user_id之前销毁了会话

// Destroy all the sessions variable
Session::destroy();
// Create a session variable named 'user_id'
Session::put("user_id", $user_id);