检查表单更改后无法单击输入

Unable to click input after checking for form changes

这是我第一次post来这里,所以请保持温柔。

我试图在用户离开他们所在的页面时对表单执行自动保存。主要是当用户一直在处理记录,然后继续导航到新记录而不先保存他们的工作时。到目前为止,我已经能够成功检测到表单内容是否已被更改,但我对如何执行保存挂断了。

这是我认为可行的代码:

var $formContents = $(document.getElementById("allData"));
origForm = $formContents.serialize();

window.onunload = function() {
   var $formContents = $(document.getElementById("allData"));
   nowForm = $formContents.serialize();

   if (nowForm !== origForm) {
      console.log('Changes detected.');
      document.getElementById('saveBut').click();
   }
   else {
      console.log('No changes detected');
   }
}

现在,数据比较工作正常。如果我更改了表单中的任何内容,我会在控制台中收到 "Changes detected" 注释。如果我还没有,我会得到 "No changes detected."

然而,"document.getElementById('saveBut').click();" 不是 运行ning,并且控制台没有显示任何错误。 'saveBut' 输入包含在 post 方法表单中,它触发 php 代码将表单数据保存到我的 SQL 服务器。

FWIW,这是输入中的 html:

<form method="post" id="save">
   <input type="submit" form="allData" value="Save Changes" id="saveBut" name="saveBut"/>
</form>

<form method="post" id="allData">
   <input type="hidden" name="formData[]" value="<?php echo $row['ID']; ?>">
   <div class="info">
      Sermon Date: <input type="date" name="formData[]" value="<?php echo $row['sermon_date']; ?>">
      Sermon Location: <input type="text" name="formData[]" value="<?php echo $row['sermon_location']; ?>">
      Call to Worship: <input type="text" name="formData[]" value="<?php echo $row['call_to_worship']; ?>">
      Hymn of Response: <input type= "text" name="formData[]" value="<?php echo $row['hymn_of_response']; ?>">
   </div>

   <br><hr style="width:90%"><br>

   <div class="top">
      Pericope:
      <input type="text" size="40" name="formData[]" value="<?php echo htmlspecialchars($row['pericope'], ENT_QUOTES); ?>">
//and on and on...
</form>

我也试过通过替换

直接调用php代码
document.getElementById('saveBut').click();

与:

$.get('saverec.php', function(data) {
   eval(data);
});

然后我尝试了:

$.ajax({
   type: "GET",
   url: "saverec.php"
});

但都没有用,我仍然在控制台日志中得到相同的结果 "Changes detected",但没有错误。我确定我遗漏了一些非常基本的东西,但我不知道那可能是什么。

有没有办法让我的 saverec.php 代码以这种方式 运行,或者我需要放弃这个烂摊子并想出不同的方法?


编辑:

我正在添加 saverec.php 文件中的代码。仅供参考,此代码没有任何问题,因为当用户单击 'saveBut' 输入时它 运行 没问题。

<?php

$location = "i.p.add.ress";
$username = "my_username";
$password = "my_password";
$dbname = "my_database_name";
$tableName = "my_table_name";
$conn = new mysqli($location, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$allData = $_POST['formData'];
$currentID = $allData[0];

//write the form data to the new record
class updateRecord {
    public function __construct ($colName, $data, $currentID) {
        $this->colName = $colName;
        $this->data = $data;
        $this->currentID = $currentID;
    }

    public function writeDataText() {
        global $conn;
        $ID = strval($this->currentID);
        $tableName = "sermon_prep_database";
        $sql = "UPDATE " . $tableName . " SET " . $this->colName . "='" . mysqli_real_escape_string($conn, $this->data) . "' WHERE ID=" . $this->currentID;
        mysqli_query($conn, $sql);
    }
}

//write all the data to the proper columns
$row = new updateRecord('sermon_date', $allData[1], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_location', $allData[2], $currentID);
$row->writeDataText();
$row = new updateRecord('call_to_worship', $allData[3], $currentID);
$row->writeDataText();
$row = new updateRecord('hymn_of_response', $allData[4], $currentID);
$row->writeDataText();
$row = new updateRecord('pericope', $allData[5], $currentID);
$row->writeDataText();
$row = new updateRecord('pericope_texts', $allData[6], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_text', $allData[7], $currentID);
$row->writeDataText();
$row = new updateRecord('fcft', $allData[8], $currentID);
$row->writeDataText();
$row = new updateRecord('gat', $allData[9], $currentID);
$row->writeDataText();
$row = new updateRecord('cpt', $allData[10], $currentID);
$row->writeDataText();
$row = new updateRecord('purpose_bridge', $allData[11], $currentID);
$row->writeDataText();
$row = new updateRecord('fcfs', $allData[12], $currentID);
$row->writeDataText();
$row = new updateRecord('gas', $allData[13], $currentID);
$row->writeDataText();
$row = new updateRecord('cps', $allData[14], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_title', $allData[15], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_scripture', $allData[16], $currentID);
$row->writeDataText();
$row = new updateRecord('text_outline', $allData[17], $currentID);
$row->writeDataText();
$row = new updateRecord('research_notes', $allData[18], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_outline', $allData[19], $currentID);
$row->writeDataText();
$row = new updateRecord('illustrations', $allData[20], $currentID);
$row->writeDataText();
$row = new updateRecord('sermon_manuscript', $allData[21], $currentID);
$row->writeDataText();

echo "<script type='text/javascript'>
    alert ('Changes saved to ID ' + $currentID);
</script>";

Ajax 调用应该有效,你试过了吗:

$.ajax({
   url: "saverec.php",
   success: function(data){
      console.log('Changes saved.');
   }
 }); 

而且你应该只有一种形式来获取数据:

<form method="post" id="save">
   <input type="hidden" name="formData[]" value="<?php echo $row['ID']; ?>">
   <div class="info">
      Sermon Date: <input type="date" name="formData[]" value="<?php echo $row['sermon_date']; ?>">
      Sermon Location: <input type="text" name="formData[]" value="<?php echo $row['sermon_location']; ?>">
      Call to Worship: <input type="text" name="formData[]" value="<?php echo $row['call_to_worship']; ?>">
      Hymn of Response: <input type= "text" name="formData[]" value="<?php echo $row['hymn_of_response']; ?>">
   </div>

   <br><hr style="width:90%"><br>

   <div class="top">
      Pericope:
      <input type="text" size="40" name="formData[]" value="<?php echo htmlspecialchars($row['pericope'], ENT_QUOTES); ?>">
//and on and on...
   <input type="submit" form="allData" value="Save Changes" id="saveBut" name="saveBut"/>
</form>

以防万一有人无意中发现这个问题,我想我应该添加最终让我在 onbeforeunload 时自动保存表单的代码:

//get the initial state of the form and store it into a variable
var $formContents = $(document.getElementById("allData"));
origForm = $formContents.serialize();

window.onbeforeunload = function() {
   //get the current state of the form on BeforeUnload and store it into a variable             
   var $formContents = $(document.getElementById("allData"));
   nowForm = $formContents.serialize();
   //compare the current state of the form with the initial state of the form             
   if (nowForm !== origForm) {
      console.log('Changes detected.');
      //use ajax to post the current form data to saverec.php
      $.ajax({
         type: 'post',
         url: 'saverec.php',
         data: nowForm,
         success: function(data){
            console.log('Changes saved.');
         }
      });
   }
   else {
      console.log('No changes detected');
   }
}

当然,这意味着即使用户不希望表单被保存,也可以保存该表单,但这可以通过覆盖此 onbeforeunload 代码的某种取消按钮轻松补救。而且,这个应用真的不是问题