没有按钮或页面刷新的Ajax更新textarea

问题描述 投票:0回答:1

我正在尝试创建一个自动更新数据库的textarea,而无需按下按钮或刷新页面。发生“键盘”后,将有一个倒计时2秒的计时器。如果在这2秒内没有进行其他输入,那么应该在数据库中更新数据。如果输入,则计时器将重新启动。

我在下面编写了ajax代码,它似乎不起作用。

$(document).ready(function() {
  var timer;
  $('#about').on('keyup', function() {
    var value = this.value;
    clearTimeout(timer);
    timer = setTimeout(function() {
      //do your submit here
      $("#about").submit()
      alert(value);
    }, 2000);
  });
  var about = $('#about').val().trim();
  $.ajax({
    url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
    type: 'post',
    data: {
      about: about
    },
    success: function(response) {
      $('#cid').val(response);
    }
  });
});
/* This is comment.php */

<?php
session_start();
require_once 'config/config.php';
require_once 'includes/auth_validate.php';

$cid = $_GET['customer_id'];
$about = $_POST['about'];

$sql = ("UPDATE patient_id SET about = ? WHERE id = ?;");

$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "si", $about, $cid);
mysqli_stmt_execute($stmt);
?>
javascript php ajax
1个回答
0
投票

将ajax移动到超时,而不是执行提交,因为您要使用ajax进行更新。

$(document).ready(function() {
  var timer;
  $('#about').on('input', function() {
    var value = this.value;
    clearTimeout(timer);
    timer = setTimeout(function() {
      alert(value);
      $.ajax({
        url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
        type: 'post',
        data: {
          about: value
        },
        success: function(response) {
          $('#cid').val(response);
        }
      });
    }, 2000);
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.