简体   繁体   English

div的内容未插入数据库

[英]Content of div not being inserted into database

I have a div which uses contenteditable to allow the user to edit the text inside it. 我有一个div,它使用contenteditable来允许用户编辑其中的文本。

When the form is submitted, I use Javascript to set a hidden input field's value as the content of the div, which is then inserted into a database. 提交表单后,我使用Javascript将隐藏的输入字段的值设置为div的内容,然后将其插入数据库中。

My issue is that the div's content isn't entered into the database. 我的问题是div的内容未输入数据库。

<?php
if(isset($_POST['submit'])) {
echo'
<script>
  document.getElementById("hiddenTextarea").value =  
    document.getElementById("post").innerHTML;
  return true;
</script>
';

$post = $_POST['hiddenTextarea'];
$stmt = $con->prepare("INSERT INTO posts (post) VALUES (:post)");
$stmt->bindParam(':post', $post);
$stmt->execute();
}
?>

<form method="post">
<div id="post" contenteditable></div>
<input type="hidden" id="hiddenTextarea" name="hiddenTextarea">
<input type="submit" name="submit">
</form>

Could the issue possibly that the query is executing before the Javascript code has changed the value of #hiddenTextarea ? 在Javascript代码更改#hiddenTextarea的值之前可能正在执行查询的问题?

Use from following code: 使用以下代码:

<?php
if(isset($_POST['submit'])) {
     $post = $_POST['post'];
     $stmt = $con->prepare("INSERT INTO posts (post) VALUES (:post)");
     $stmt->bindParam(':post', $post);
     $stmt->execute();
}
?>

<form method="post">
     <textarea name="post"></textarea>
     <input type="hidden" id="hiddenTextarea" name="hiddenTextarea">
     <input type="submit" name="submit" onsubmit="return copyContent()">
</form>

After various suggestions from different forums and various users, I was able to come up with a solution using Javascript's onkeyup event: 经过来自不同论坛和用户的各种建议,我能够使用Javascript的onkeyup事件提出一个解决方案:

<?php
if(isset($_POST['submit'])) {
$post = $_POST['hiddenTextarea'];
$stmt = $con->prepare("INSERT INTO posts (post) VALUES (:post)");
$stmt->bindParam(':post', $post);
$stmt->execute();
}
?>

<form method="post">
<div id="post" contenteditable></div>
<input type="text" name="hiddenTextarea" id="hiddenTextarea">
<input type="submit" name="submit">
</form>

<script>
var contentText = document.getElementById('post');
var hiddenInput = document.getElementById('hiddenTextarea');
contentText.onkeyup = function() {
    hiddenInput.value = this.innerHTML; 
};
</script>

When the user types in the contenteditable div, it's also automatically typed into the hidden input field, which can then be defined through a variable and entered into the database. 当用户键入contenteditable div时,它也会自动键入到隐藏的输入字段中,然后可以通过变量定义该字段并输入数据库。

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

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