简体   繁体   English

Ajax更新textarea,无需按钮或页面刷新

[英]Ajax update textarea without button or page refresh

I am trying to create a textarea that automatically updates the database without the need to press a button or refresh the page. 我正在尝试创建一个自动更新数据库的文本区域,而无需按按钮或刷新页面。 After a "keyup" occurs there will be a timer that will countdown for 2 seconds. 发生“键控”后,将有一个计时器将倒计时2秒钟。 If no other input is made within those 2 seconds then that the data should be updated in the database. 如果在这2秒钟内未进行任何其他输入,则应在数据库中更新数据。 If a input is made the timer will restart. 如果输入,计时器将重启。

I've written the ajax code below, it doesn't seem to work. 我已经在下面编写了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); ?> 

Move the ajax into the timeout, rather than performing the submit, since you want to update with ajax. 将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); }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM