Below is the Java Script code to display a text box on clicking a Reply button.
while($row = mysqli_fetch_array( $results )) {
echo "<div class='cmt'>
<div class='cmttext'></div>
<button class='replybtn'>Reply</button>
<div class='replyform'></div>
</div> ";
}
and java script
<script type="text/javascript">
var varHtml = "<form method='post' action=''><textarea name='reply'></textarea> <input type='button' value='Cancel' onclick='history.go(0)' /> <input type='submit' /> </form>";
var allElements = document.body.getElementsByClassName("replybtn");
var addCommentField = function() {
for (var i = 0; allElements.length > i; i++) {
if (allElements[i] === this) {
console.log("this " + i);
if (document.getElementsByClassName("replyform")[i].innerHTML.length === 0) {
document.getElementsByClassName("replyform")[i].innerHTML = varHtml;
}
}
}
};
for (var i = 0; i < allElements.length; i++) {
allElements[i].addEventListener('click', addCommentField, false);
}
</script>
How can I get the values from text box and store it into database?
Assuming you want to use Ajax, you'll need to attach a click handler to the button, which will grab the relevant values and send them to a server-side script (eg PHP) which can then insert them into the db.
(If you don't want to use Ajax, just use a form and submit it like normal).
Here's a generic example (using jQuery) which does that. You can adapt it to your needs:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Ajax example</title>
</head>
<body>
<form action="">
<input type="text" id="myTextField" />
<button>Submit</button>
</form>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function submitValuesToDatabase(values){
$.ajax({
url: '/path/to/submit.php',
type: 'POST',
data: values
})
.done(function(res) {
console.log("success");
console.log("The server replied: " + res);
})
.fail(function(err) {
console.log("Something went wrong!");
console.log(err);
})
.always(function() {
console.log("complete");
});
}
$("button").on("click", function(e){
e.preventDefault();
var values = {
val1: $("#myTextField").val()
}
submitValuesToDatabase(values);
});
</script>
</body>
</html>
submit.php
<?php
// Retrieve values from $_POST
// And insert them into database
print_r($_POST);
If you run this demo (on a server), you will see output resembling the following in the console:
success
The server replied: Array
(
[val1] => rtzr
)
complete
So, in this case to get a reference to val1 in the PHP script you would do:
$val1 = filter_var($_POST['val1'], FILTER_SANITIZE_STRING);
Let me know if that's unclear.
Edit: The .always()
.fail()
and .done()
callbacks are not stricly necessary. I included them for demonstration purposes, but feel free to leave them out.
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.