php textarea使用jquery/ajax自动保存到sql

标签 php jquery mysql ajax textarea

我知道这个问题之前已经被问过,并且我已经阅读了一些建议和答案,但我无法让它发挥作用。

我在 php 页面上有一个文本区域,我想在用户输入时或每 2-5 秒将文本区域的内容保存到 SQL 数据库中,而无需重新加载页面。

我相信它必须用 jquery 和 Ajax 制作?

如果我将其作为带有保存按钮的 POST 表单,内容将保存到数据库中 - 所以我知道 sql 正在运行。

我有这些文件: 待办事项.php

<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<form method='post' action='notes.php'>
<table border='0' cellspacing='0' width='480px' height='250px' align='center' id='logo-table'>
<tr>
<td align='center' height='10px' valign='top'><textarea type='text' id='notes_input' name='notes_input' style='width: 460px; height: 230px; border:0px;'>$data[notes]</textarea></td>
</tr>
</table>
<input type='image' src='/nycrm/grafik/Save-as.png' name='gem' value='Submit' />
</form>

和 script.php

<?php
require_once 'connect.php';
session_start();
$ses_userid = $_SESSION['ses_userid'];
$notes_input = $_POST["notes_input"]; 

mysqli_query($connect_intra, "UPDATE user SET notes = '$notes_input' where userid = '$ses_userid'");
 ?>

我尝试了在 stackoverflow 上找到的这段代码,但似乎代码没有被执行 - 在这种情况下,todo.php 看起来像这样:

<?php

$ses_userid = $_SESSION['ses_userid'];
$query =  mysqli_query($connect_intra, "SELECT notes FROM user WHERE userid = '$ses_userid'");
$data = mysqli_fetch_array($query);

echo"
<script type=\"text/javascript\" src=\"//code.jquery.com/jquery-1.9.1.js\"></script>
<script type=\"text/javascript\">
$(\"#notes_input\").bind(\"keydown\", function() { myAjaxFunction(this.value); });

function myAjaxFunction(value) {
$.ajax({
    url: \"script.php\",
    type: \"POST\",
    data: \"notes_input=\" + value,
    success: function(data) {
        if (!data) {
            alert(\"unable to save file!\");
        }
    }
});
}
</script>
<form method='post' action='notes.php'>
<table border='0' cellspacing='0' width='480px' height='250px' align='center' id='logo-table'>
<tr>
<td align='center' height='10px' valign='top'><textarea type='text' id='notes_input' name='notes_input' style='width: 460px; height: 230px; border:0px;'>$data[notes]</textarea></td>
</tr>
</table>
<input type='image' src='/nycrm/grafik/Save-as.png' name='gem' value='Submit'/>
</form>
";
?>

我是否错过了一些东西,所以它会起作用?

非常感谢您的帮助。

/托马斯。

最佳答案

浏览器从上到下读取 HTML。当它找到脚本标签时,它会暂停解析并评估脚本。

在您的示例中,当第二个脚本启动时,textarea 还不存在。 由于jquery找不到任何id为notes_input的节点,它只是创建空的jquery对象以防止进一步函数中出现错误。

您应该将第二个脚本(带有 .bind 语句)移至 body 标记的末尾,或将出价包装到 jquery.ready 函数。它将延迟脚本的执行,直到页面完全解析。

关于php textarea使用jquery/ajax自动保存到sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37929629/

相关文章:

php - 带有 SET 变量语句的 Mysqli 查询(即多个查询)

php - 禁止获取 twitch channel 源

javascript - 在 javascript 对象中使用 jquery

jquery - Jackson 无法读取文档 : Unrecognized token 'contactForm' : was expecting ('true' , 'false' 或 'null' )

MYSQL检查是否存在日期链

php - Laravel Eloquent,如何用公式定义表关系?

javascript - 自动提交表单到HTTPS站点,如何进行身份验证?

php - 从没有 ID 的表中删除 maxdate

jQuery 获取类

php - PHP 中的未知 MySQL 服务器主机错误