javascript 从 php 自动保存到 mysql,无需页面更改或提交按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18145796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:52:36  来源:igfitidea点击:

Autosave from php to mysql without page change or submit button

phpjavascriptmysqlautosave

提问by snookian

Basically I have a list of data that is shown via a foreach statement from a table in my database. I want a dropdown list next to each that has some values in them that need to be saved to a field in my table, however I want to autosave the value in the dropdown list to the field as soon as the value in it is changed. Can anyone point me to a tutorial or something that might help?

基本上,我有一个数据列表,通过我数据库中的表中的 foreach 语句显示。我想要每个旁边都有一个下拉列表,其中有一些值需要保存到我的表中的字段中,但是我想在下拉列表中的值更改后立即将其自动保存到该字段中。谁能指出我的教程或可能有帮助的东西?

I am using php and mysql to create the system, but will happily use JavaScript if required

我正在使用 php 和 mysql 来创建系统,但如果需要,我会很乐意使用 JavaScript

I have had a look at this: dynamic Drive Autosavehttp://www.dynamicdrive.com/dynamicindex16/autosaveform.htmwhich is similar to what i want, however i need it to actually store that data in my database not temporary storage.

我看过这个:dynamic Drive Autosave http://www.dynamicdrive.com/dynamicindex16/autosaveform.htm与我想要的类似,但是我需要它来实际将数据存储在我的数据库中而不是临时存储中。

Any Guidance appreciated,

任何指导表示赞赏,

Ian

伊恩



BIG EDIT

大编辑

So, thankyou for the replys but I have no clue about ajax call.....I found this:How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?.

所以,谢谢你的回复,但我对 ajax 调用一无所知......我发现了这个:如何在没有提交按钮的情况下将 ComboBox 中的选择自动保存到 PHP 中的 MYSQL 中?.

can i get it to work?

我可以让它工作吗?

<script>
$(document).ready(function(){
$('select').live('change',function () {
        var statusVal = $(this).val();
        alert(statusVal);
        $.ajax({
                 type: "POST",
                 url: "saveStatus.php",
                 data: {statusType : statusVal },
                 success: function(msg) {
                     $('#autosavenotify').text(msg);
                 }
      })
  });
});
</script>


<?php foreach ( $results['jobs'] as $job ) { ?>

          <td width="25%"><?php echo $job->job_id</td> 
          <td>
          <select name="status" id="status">
                  <option value=''>--Select--</option>
                  <option value='0'>Approve</option>
                  <option value='1'>Reject</option>
                  <option value='2'>Pending</option>
          </select>
          <div id="autosavenotify"></div>
          </td>
        </tr>
    <?php } ?>

and on the page saveStatus.php:

并在页面 saveStatus.php 上:

<?php
if (isset($_POST['statusType'])) {

$con=mysql_connect("localhost","username","mypass","rocketdb3");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("jobs", $con);

$st=$_POST['statusType'];
    $query = "UPDATE jobs SET status=$st WHERE job_id=$id";
    $resource = mysql_query($query) 
        or die (mysql_error());

}
?>

回答by mrami0

Where is the $idin saveStatus.php ?

saveStatus.php 中的$id在哪里?

You need to pass the statusType and job_id via AJAX to update correctly in the saveStatus.php.

您需要通过 AJAX 传递 statusType 和 job_id 才能在 saveStatus.php 中正确更新。

For example:

例如:

<script>
$(document).ready(function(){
$('select').on('change',function () {
        var statusVal = $(this).val();
        var job_id = $(this).id;
        alert(statusVal);
        $.ajax({
                 type: "POST",
                 url: "saveStatus.php",
                 data: {statusType : statusVal, job_id: job_id },
                 success: function(msg) {
                     $('#autosavenotify').text(msg);
                 }
      })
  });
});
</script>


<?php foreach ( $results['jobs'] as $job ) { ?>

      <td width="25%"><?php echo $job->job_id; ?></td> 
      <td>
      <select name="status" id="<?php echo $job->job_id; ?>">
              <option value=''>--Select--</option>
              <option value='0'>Approve</option>
              <option value='1'>Reject</option>
              <option value='2'>Pending</option>
      </select>
      <div id="autosavenotify"></div>
      </td>
    </tr>
<?php } ?>

*Note: .live()is deprecated, use .on()instead.

*注意:.live()已弃用,请.on()改用。

And saveStatus.php

和 saveStatus.php

$st = (int)$_POST['statusType'];
$id = (int)$_POST['job_id'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";

回答by Mohd Shibli

You can use the JavaScript onchange listener on the select element something like this

您可以在 select 元素上使用 JavaScript onchange 侦听器,如下所示

<select onchange="savedata()">

savedata() function is nothing but your AJAX code i have found an AJAX script which takes content from text fields and save it into the database you can modify it according to your need.

savedata() 函数只不过是您的 AJAX 代码,我发现了一个 AJAX 脚本,它从文本字段中获取内容并将其保存到数据库中,您可以根据需要对其进行修改。

function getData(){


var fd = new FormData();

  var title = document.getElementsByName('title')[0].value;
  var content = document.getElementsByName('content')[0].value;
  var id = document.getElementsByName('id')[0].value;
  fd.append('title',title);
  fd.append('content',content);
  fd.append('id',id);

  return fd;
}

function savePost(){
  try{
    var xhttp = new XMLHttpRequest();
  }
  catch(e){
    console.log(e);
  }
  var data = getData();
  xhttp.open('POST','autosave.php?save=true');
  xhttp.send(data);
  xhttp.onreadystatechange = function(){
    if(this.status == 200 && this.readyState == 4){
      if(data.get('id') == ""){
        document.getElementsByName('id')[0].value = this.responseText;
      }
      else{
        document.getElementById('message').innerHTML = this.responseText;
      }
      console.log(this.responseText);
    }
  }
}

setInterval(savePost,10000); //savePost will be called in every 10 seconds

The PHP script for database insertion and updation is as follows

数据库插入和更新的PHP脚本如下

date_default_timezone_set('Asia/Kolkata'); //you can add your own timezone
$host = 'localhost';
$user = 'your_db_username';
$pass = 'your_db_password';
$db = 'autosave';
$conn = new mysqli($host, $user, $pass, $db);
function insertPost($title,$content, $conn){
  $sql = "INSERT INTO post VALUES(null, ?, ?)";
  $stmt = $conn->stmt_init();
  if($stmt->prepare($sql)){
    $stmt->bind_param('ss',$title,$content);
    if($stmt->execute()){
      echo $conn->insert_id;
    }
  }}

function updatePost($title,$content,$id, $conn){
  $sql = "UPDATE post SET title = ?, content = ? WHERE id = ?";
  $stmt = $conn->stmt_init();
  if($stmt->prepare($sql)){
    $stmt->bind_param('ssi',$title,$content,$id);
    if($stmt->execute()){
      echo "<i>Draft Saved at ".date("h:i:s a")."</i>";
    }
  }}
if(isset($_GET['save'])){
  $title = $_POST['title'];
  $content = $_POST['content'];
  $id = $_POST['id'];
  if($id != ''){
    updatePost($title, $content,$id, $conn);
  }
  else{
    insertPost($title, $content, $conn);
  }}
?>

You can find the code and complete tutorial on the following link: Data Autosave System using PHP, MySQL and AJAX

您可以在以下链接中找到代码和完整教程:使用 PHP、MySQL 和 AJAX 的数据自动保存系统

回答by Borniet

You will need to use JavaScript (+ jQuery for easier working) to achieve this. Catch the 'change' of the value using JavaScript and fire an AJAX call to a PHP script that saves the value to the MySQL db.

您将需要使用 JavaScript(+ jQuery 以便于工作)来实现这一点。使用 JavaScript 捕获值的“更改”并向 PHP 脚本发出 AJAX 调用,该脚本将值保存到 MySQL 数据库。

回答by Deepak Biswal

Use jQuery! On the drop-down onchange event do a ajax call and update the record in DB. Here is a link to jQuery Ajaxmethod.

使用jQuery!在下拉 onchange 事件上执行 ajax 调用并更新数据库中的记录。这是jQuery Ajax方法的链接。