I am attempting to implement a feature on my website, where a user can input a comment into a textarea and have it display the comment, below the comment box. For backend I am using bottle. At the moment, bottle is recognizing the input, and when input is submitted, a new url loads displaying only the input of the textarea. When submitted, I need the textarea input to be displayed below the textarea box, without changing the webpage.
Here is HTML textarea input
<div>
<p>
Add a comment
</p>
<form action="/comment" method="post">
<textarea name="text"></textarea>
<input type="submit" value="Submit">
</form>
</div>
Bottle in main.py
@route('/comment', method = 'POST')
def submit():
com = request.forms.get('text')
print('Printing comment...')
print(com)
return com
index.js, (i'm not sure how to integrate this function)
function loadCom () {
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
console.log(this.response);
document.getElementById("dcom").innerHTML = this.response;
}
};
xhttp2.open("GET", "/comment");
xhttp2.send();
return false
}
Call loadCom() from an event listener.
document.querySelector("form").addEventListener("submit", e => {
e.preventDefault(); // prevent reloading the page
loadCom();
});
loadCom() needs to use the POST method to send the value of the textarea to the controller.
function loadCom () {
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
console.log(this.response);
document.getElementById("dcom").innerHTML = this.response;
}
};
xhttp2.open("POST", "/comment");
xhttp2.send('text=' + encodeURIComponent(document.querySelector('[name="text"]').value);
return false
}