【问题标题】:Updating MySQL field beforeunload卸载前更新 MySQL 字段
【发布时间】:2015-02-19 22:10:23
【问题描述】:

我正在开发一个 CMS,以允许用户访问和分类 MySQL 数据库中的记录。我为此 CMS 创建了一个用户登录系统。我正在尝试编写一个锁定功能,该功能将监视何时查看记录,以便其他用户无法访问此记录。这是为了防止多个用户同时尝试写入同一记录。

到目前为止,这部分工作得很好。当他们访问记录时,我会在 MySQL 数据库中更新该特定记录的“in_use”字段以显示它正在被查看。当他们提交了带有记录分类的表单后,我更新了“in_use”字段以显示它不再被查看。

我遇到的问题是当用户关闭浏览器而不提交表单,或者当他们离开页面时。

我一直在尝试使用 AJAX 对 beforeunload 事件运行更新,但它一直没有工作。

***** readRecord.php*****

<h1>Analyze</h1>

//PHP include that contains functions for php queries to the MySQL database.

<?php
    include 'core/database/record_functions.php';
?>

//Form to search MySQL database by Case Number and Button to manually release a record that is in_use.

<form action="" method="post">

<p id="case_search">Search records by Case Number: <input type="text" id="case_num_field" name="case_num">

<input type="text" name="in_use" id="in_use" readonly="readonly" hidden="hidden" value="1">

<input type="text" name="user" id="user" readonly="readonly" hidden="hidden" value="<?php echo $_SESSION['username']; ?>">

<input type="submit" name="Submit" value="Select" id="case_num_submit">

<input type="Submit" name="release record" value="Release the current record" onclick="<?php update_in_use($_SESSION['case_num'], 0); ?>">
</p>

</form>

//Includes for jQuery library and AJAX code for automatically releasing the record on page navigation or close.

<script type="text/javascript" src="core/jquery-2.1.3.js"></script>
<script type="text/javascript" src="ajaxBridge.js"></script>

... code continues for reading records
... when the form is submitted update_in_use is called again to set the value to 0

***** ajaxBridge.js *****

// This code is supposed to run the query on releaseVariable.php to update the in_use field to 0 on the beforeunload event.

window.addEventListener("beforeunload", function(event){
   if(xmlHttp.readyState==4)
   {
    xmlHttp.open("POST", "releaseVariable.php", true);
    xmlHttp.send();
    event.returnValue = "Hey it worked!";
   }
   event.returnValue = "Hey it failed!";
   });

***** releaseVariable.php *****

// This simply runs the update_in_use function to set the in_use field to 0 for this particular case.

<?php
include 'core/init.php';
include 'read_record.php';
protect_page();

update_in_use($_SESSION['case_num'], 0);

?>

我这样做的方式是否正确?如果不是,我该如何解决这个问题?

如果这是一个好方法,我在哪里误入歧途的代码?

【问题讨论】:

  • 我也刚刚意识到我忘记在 ajaxBridge.js 文件中的 if 语句中添加 else ... 哎呀
  • 在查看 readRecord.php 的下半部分时,我发现我无意中分配了两个具有相同名称和 ID 为“in_use”的输入。无论我何时尝试使用 ajax 更新,这可能都会导致设置值。虽然,它似乎仍然会在之后运行并发布记录。

标签: javascript php mysql ajax onbeforeunload


【解决方案1】:

我决定放弃这种方法,改用 php SESSION 变量。

【讨论】:

    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2015-04-25
    • 2011-05-21
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    相关资源
    最近更新 更多