简体   繁体   中英

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.

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.

My issue is that the div's content isn't entered into the database.

<?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 ?

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:

<?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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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