This is a follow up to my other question. I am asking again because this seems more a javascript question than a Google App Engine question.
I have a form
<form name="choice_form" id="choice_form" method="post" action="/g/choicehandler" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>
I want to take the value of this textarea and send it to the app with formData. I tried this
var choice = document.getElementById("choice_form").value;
but I get “undefined” for the value of “choice”. What am I doing wrong?
And also, if I understand correctly, the /g/choicehandler is called twice once by the form and once by the XHR. How do I fix that? Below is the handler:
class Choice(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<head>
<script type="text/javascript">
var count = 0;
function writeToStorage()
{
var user = "user" + count;
count++;
localStorage.setItem("chooser", user);
var choice = document.getElementById("choice_form").value;
var formData = new FormData();
formData.append("chooser", user);
formData.append("choice", choice);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8086/g/choicehandler", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4 && xhr.status == 200){
console.log("request 200-OK");
}
else {
console.log("connection error");
}
};
xhr.send(formData);
//added this per Aaron Dufour's answer
return 0;
};
</script>
</head>
<body>
//changed onsubmit like this: onsubmit="return writeToStorage(); as per Aaron Dufour's answer
<form name="choice_form" id="choice_form" action="/g/choicehandler" method="post" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>
</body>
</html>""")
UPDATE
See Aaron Dufour’s answer for the solution.
As others have said, you’re accessing the
form, when the data you want is in thetextarea. If you give thetextareaan ID, that’s probably the easiest way to get to its value.After much discussion, we determined that you don’t need XHR at all. Here’s what your form should look like:
And now, we use the javascript function to edit the form before allowing it to be submitted: