在卸载之前更新MySQL字段

时间:2015-02-19 22:10:24

标签: javascript php mysql ajax onbeforeunload

我正在使用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);

?>

我是以正确的方式来做这件事的吗?如果不是,我该如何解决这个问题?

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

1 个答案:

答案 0 :(得分:0)

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