I am trying to obtain the form values from JavaScript. The HTML code of the form is:
<form action="./ExampleServlet" method="POST" id="myform">
<label>Username</label>
<input type="text" name="user"><br>
<label>Password</label>
<input type="password" name="pswd" id="launchX"><br>
<div class="action_btns">
<div class="one_half last" id="loginButton">
<a onclick="document.getElementById('myform').submit();" class="btn btn_red">Login</a>
</div>
<div class="one_half last" id="bottonBack">
<a href="#closeButton" class="btn btn_red">Back</a>
</div>
</div>
</form>
$(function(){
$("#launchX").keypress(function (e) {
if (e.keyCode == 13) {
alert('You pressed enter!');
$.ajax({
type: "POST",
url: "./ExampleServlet",
//data: {formValues: "formValues="+JSON.stringify($("#myform"))}
data : {
formValues: "formValues=" + $("#myform")[0].action
}
});
}
});
});
How can I send to my servlet only the values for the form (user and pswd parameters)?
Note 1: I commented //data: {formValues: "formValues="+JSON.stringify($("#myform"))} to toggle in-out some server-side console output tests.
Note 2: in this case the form $("#myform")[0].action returns correctly printing the url of the servlet. I tried also $("#myform")[0].method and it returns post as a string as expected.
Note 3: the form JSON.stringify($("#myform")) returns the entire "form object" and it prints all the form fields, but I can't find the field "user" and "pswd", i.e. the parameters I need.
I suppose to use $('#myform').serialize() but I'm not sure.