【问题标题】:AJAX jQuery not working when querying to the database查询数据库时 AJAX jQuery 不起作用
【发布时间】:2018-12-01 06:49:25
【问题描述】:

在我的代码中,我从用户那里得到了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”)会收到警报。那么,我做错了什么?

【问题讨论】:

  • 您是否在主文件中添加了这一行:

标签: javascript php jquery ajax laravel-5.2


【解决方案1】:

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

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

【讨论】:

  • 那有什么作用?
  • 我认为它的工作方式类似于 session_destroy(); php.net/manual/en/function.session-destroy.php。使用 Session::flush(); // 删除所有会话数据
  • 所以,session::forget("user_id");应该管用?让我们试试吧!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 2014-05-24
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多