JSP: using javascript to submit form - javascript

(I know the questions is a bit long but I do believe solution is easy, so would really appreciate it if someone can help me have a look)
I am trying to write a school system, where you can enter a student's name, year, grade, on a webpage, and save the student's info to produce a list. I would like it to have two "buttons" on the webpage:
One is "save and next", i.e. if you finished entering one student info, click this, the info get saved and the webpage renew to enter the next student info.
Second is "save and finish", i.e. if this is the final student you want to enter, click this and the last student info get saved, and webpage is redirected to the next page where it shows a list of all student info.
To achieve this, in JSP, I used two HTML forms, and one of them I used javascript to try to submit to servlet, But I must have done something wrong because it does not work properly:
Here are my codes:
InputGrade.jsp:
<html>
<head>
<title>Title</title>
</head>
<body>
The first form: used input labels for users to enter info, also used input label to create a submit button "save it next":
<form action = "InputGradeServlet" method="POST">
<table>
<tr>
<td>
Enter Student Name: <input type="text" id="stName" name = "stName" />
</td>
<td>
Enter Subject: <input type="text" id="Subject" name = "Subject" />
</td>
<td>
Enter Grade: <input type = "text" id="Grade" name = "Grade" />
</td>
<td>
<input type="submit" value="save and next"/>
</td>
</tr>
</table>
<input type="text" name = "flag" style="display: none" value="1"/>
</form>
The second form include the "save and finish" button, but use javascript to submit the information: (I think where the problem is)
User still enter student info in the first form, but the javascript function use getElementById function to acquire the info in first form
<form name="form2" action ="InputGradeServlet" method="POST" >
<input type="text" name = "flag" style="display: none" value="2"/>
<button onclick="finSaveFunc()">Finish and submit</button>
<script>
function finSaveFunc() {
var stName = document.getElementById("stName")
var Subject = document.getElementById("Subject")
var Grade = document.getElementById("Grade")
document.stName.submit();
document.Subject.submit();
document.Grade.submit();
}
</script>
And in the Servlet, a list created to add the students the user entered
public class InputGradeServlet extends HttpServlet {
List<Student> inputStList = new <Student>ArrayList();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if user press "save and next" button, form one is submitted, and servlet do the action of saving student to the list and redirect to the same JSP file i.e. redirect the the same webpage again of entering the next student:(also might be problematic)
if (request.getParameter("flag").equals("1")) {
request.getParameter("Grade");
...... (get other info: name, year ect)
inputStList.add(findstudent); //add student entered to the list
response.sendRedirect("InputGrade.jsp");
}
}
}
If user press "save and finish", i.e. submitting the second form, and servlet again add the final student entered to the list and redirect to the next webpage showing the whole list:
}else if (request.getParameter("flag").equals("2")) {
request.getParameter("Grade");
....
inputStList.add(findstudent);
request.getSession().setAttribute("inputStList",inputStList);
response.sendRedirect("ShowList.jsp"); }
This is where it gets problematic: when submitting the first form hitting "save and next" button it works fine, but when submitting the second from hitting "save and finish" button, it returns error.
Therefore I would really appreciate it if some can help me have a look?

There are many reason that's why you can get a NullpointerException.
Rule of Thumbs : If you want to compare a string then first check if it is not null.
According to your requirement I am giving a solution that how can you do that.
Suppose your form be like:
<html>
<head>
<script>
function _submit(flagVal) {
document.getElementById('flagValId').value=flagVal;
document.getElementById('someFormId').submit();
}
</script>
</head>
<body>
<form action = "InputGradeServlet" method="POST" id="someFormId">
<table>
<tr>
<td>
Enter Student Name: <input type="text" id="stName" name ="stName" />
</td>
<td>
Enter Subject: <input type="text" id="Subject" name = "Subject" />
</td>
<td>
Enter Grade: <input type = "text" id="Grade" name = "Grade" />
</td>
<td>
<input type="button" value="save and next" onclick="_submit('1')"/>
<input type="button" value="save and exit" onclick="_submit('2')"/>
</td>
</tr>
</table>
<input type="hidden" id="flagValId" name = "flag" value=""/>
</form>
</body>
</html>
Now when you click save and next button, then it set flagVal 1 and if we click save and exit button then it sets flagVal 2. After setting the flagVal it submits the form. After submitting your from you should check first that what is your flagVal. So in doPost method
if (request.getParameter("flag")!=null && request.getParameter("flag").equals("1")) {
//Add your student in this block and show the input page again.
response.sendRedirect("InputGrade.jsp");
}else if (request.getParameter("flag")!=null && request.getParameter("flag").equals("2")) {
//Add your student in this block and show the list.
response.sendRedirect("ShowList.jsp");
}
Hope that helps.

You don't get form1 values. You post form2 values so you get null error.
Try it please:
function finSaveFunc() {
var stName = document.getElementById("stName")
var Subject = document.getElementById("Subject")
var Grade = document.getElementById("Grade")
var newForm = document
.getElementById("form2")
.appendChild(stName)
.appendChild(Subject)
.appendChild(Grade);
newForm.submit();
}

Related

posting javascript populated form to another php page

I'm trying to take some js that pulls data from another web application and populates a form by clicking "Populate Contact Info" and then click a "Submit" button to push the fields to a new php that then processes them. So basically how do I pass populated form field to a second form on the same page that I can then submit? Or is there a better way?
<form action="#" name="data" id="data">
<input type='button' value='Populate Contact Info' onclick='popAllContactFields()' />
Contact Info:
First Name: <input type='text' readonly="readonly" id='cfname' name='cfname' />
Last Name:<input type='text' readonly="readonly" id='clname' name='clname' />
Email: <input type='text' readonly="readonly" id='cemail' name='cemail' />
</form>
<script type="text/javascript">
/* popAllContactFields()
Populates all the contact fields from the current contact.
*/
function popAllContactFields()
{
var c = window.external.Contact;
{
// populate the contact info fields
popContact();
}
}
/* popContact()
Populates the contact info fields from the current contact.
*/
function popContact()
{
var c = window.external.Contact;
// set the contact fields
data.cfname.value = c.FirstName;
data.clname.value = c.LastName;
data.cemail.value = c.EmailAddr;
}
</script>
<form action="ordertest.php" method="post">
<input name="cfname" id="cfname" type="hidden" >
<input name="clname" id="clname" type="hidden" >
<input name="cemail" id="cemail" type="hidden" >
<input type="submit" value="Submit">
</form>
If you can manage to receive the data with an AJAX call as a JSON then it's vary easy. With using jQuery ($) and Lodash (_ but you can try Underscore as well):
$.get('an-url-that-returns-the-json', function(parsedData) {
_.forEach(_.keys(parsedData), function(key) {
console.log('key:', key);
$('#'+key).val(parsedData[key]);
});
});
If it's tough at first sight read some about jQuery selectors, AJAX ($.get()) and $(...).val().
You can also make a list about the keys that you want to copy, e.g. var keysToCopy = ['cfname', 'clname', 'cemail'] and then _.forEach(keysToCopy, function(key) {...}), this gives you more control with the copied data.
If you cannot use AJAX but can control the output of the source PHP, then I'd rather create the data as a raw JS object. If you cannot control the generated stuff then you must use something like you wrote, that also can be helped by some jQuery based magic, e.g.
_.forEach(keysToCopy, function(key) {
var prop = $('#source-form #'+key).val();
$('#target-form #'+key).val(prop)
});
Based on these you can think how you can solve if the source and target IDs are not the same.

Javascript Validation Conflict

I have a search bar in my header. I did a validation test on it that if it is empty and the user presses the "Search" button then it should display a dialog box saying to "Write the product name". This validation works However on a couple of pages I have a search option that lets the user enter the price range for which he/she wants to see the products. They both are distinct and two different forms but for some odd reason when I put validation on the price range form, the validation skips that and displays the same "Write the product name" dialog box and highlights the search bar red which it shouldn't do at all. What can be the reason for it?
Here's the code for the search bar validation and form
<script>
function checkforblank()
{
if(document.getElementById('search').value == "")
{
alert('Please type a product name first');
document.getElementById('search').style.borderColor = "red";
return false;
}
}
</script>
<form action ="http://localhost/MyOnlineStoreOwn/product_search_result.php" method="post">
<input type ="text"name="search" id = "search" placeholder="Search for products..." align="right" />
<input type="submit" value="Search" />
</form></td>
Here's the code for price range search box and form
function checkforblank()
{
if(document.getElementById('price1').value == "")
{
alert('Please enter price first');
document.getElementById('price1').style.borderColor = "red";
return false;
}
if(document.getElementById('price2').value == "")
{
alert('Please enter price first');
document.getElementById('price2').style.borderColor = "red";
return false;
}
}
</script>
<form action="http://localhost/MyOnlineStoreOwn/product_list_priceSearch.php" onsubmit="return checkforblank()" method="post">
$<input name="price1" type="text" id="price1" size=8 />
to <br/>
$<input name="price2" type="text" id="price2" size=8 /> <br>
<input type="submit" name="sprice" value="Go" >
</form>
UPDATE:
if(isset($_GET['deleteid']))
{
echo 'Do you really want to delete this item with ID of ' .$_GET['deleteid']. '? Yes | No';
exit(); // doesn't render the whole page, only prompts the question script.
}
how do I make a dialog box to ask the "Do you really want" part and if the user selects yes it does: Yes
and he/she selects no then it does this:
I was having trouble writing the part inside of an echo statement because of the "" or ''..how do i write the correct syntax for echo "alert('Are you sure Y/N'); if yes do this and if no do this?
You cant have two functions on the same name. Might be you are getting the alert because the search script is loaded first.
For form validation, you need to write your code is another format. check this from w3 schools.
Try different function names.

jQuery, javascript: several forms same submit button text - how to determine value of closest hidden value box

I have several forms in HTML, each with a submit button and a hidden field. The same javascript function is called when any of the submit buttons are pushed. I want to know which submit button has been pushed. I think I can do this by finding out what the hidden field value is of the corresponding form - but I'm having difficulty with this. My HTML is:
<div id="existingPhotosList">
<table><tbody><tr><td>
<img src="./userPictures/IMG0001.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0001.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
<tr>
<td>
<img src="./userPictures/IMG0002.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0002.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
</tbody>
</table>
</div>
There may be more or less table rows with images and forms on them - depending on how many images are found on the server.
The javascript I have right now is:
$('.deleteFiles').submit(deleteFile);
function deleteFile() {
var myValue = $(this).parent().closest(".picture").val();
alert(myValue);
return false;
}
I'm currently getting undefined as the result of the alert.
I want to know which submit button has been pushed.
As each of your forms only has one submit, you don't have to change your code much.
this in your submit handler will refer to the form, and the element is within the form, so:
var myValue = $(this).find("input[name=picture]").val();
No need to go up to the parent, and closest goes up the ancestry (through ancestors), not down. find goes down (descendants).
the simplest way I think will be:
var myValue = $('input[name=picture]', this).val();
should be:
var myValue = $(this).closest(".deleteFiles").find("input[type=hidden]").val();
here is the demo http://jsfiddle.net/symonsarwar/963aV/
$('.deleteFiles').click(deleteFile);
function deleteFile() {
var me=$(this).closest('tr').find('td:eq(1) input').val();
alert(me)
}

Is it possible to construct a link, navigate to it and print the response in C# programmatically? How?

I have a webpage written in C#/Razor. I am printing all the values from a database on this page like so :
<div style="min-height: 150px; font-size: 1.25em">
<div style="margin-bottom: .5em">
<table>
<thead>
<tr>
<th>Name</th>
<th>Branch</th>
<th>Phone No.</th>
<th>Extension</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var prod in Model)
{
<tr>
<td>#prod.FullName</td>
<td>#prod.Branch</td>
<td>#prod.PhoneNo</td>
<td>#prod.Extension</td>
<td>#prod.Email</td>
#if (User.IsInRole(#"Admins") || User.Identity.Name == prod.DomainAC)
{
<td>edit</td>
}
else
{
<td>User => #User.ToString()</td>
}
<td>
<input type="checkbox" name="message" value="#prod.PhoneNo">Message<br>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
This works fine to display their info. What I would like to do now is a small bit more difficult.
Below this, I have a form with a username, password and message. Using this form, I would like to have the behaviour that on submit, it will take the values in the input boxes of the form and the above C#, construct a link, navigate to the link and print the response of the server
So I have :
#{if (IsPost)
{
//handle and print response
}
else
{
<form method="post" action="">
Username:<br />
<input type="text" name="u" /><br />
Password<br />
<input type="text" name="p" /><br />
<br />
Password<br />
<textarea name="m" cols="25" rows="5">
Enter your comments here...
</textarea><br>
<br />
<input type="submit" value="Submit" class="submit" />//when this is clicked, construct url and navigate to it.
</form>
}
}
The URL I want to construct from this form is :
http://webaddress.com/web/d.php?u=<Username entered by user>&p=<Password entered by user>&s=<List of Phone Numbers from the C# above where the checkbox is selected, comma separated>&m=<Comment submitted by user>
So, if my name is "John", Password is "Password1", Comment is "Test" and I have selected one checkbox for a user with the phone number "12345678", the URL I will navigate to is :
http://webaddress.com/web/d.php?u=John&p=Password1&s=12345678&m=Test
Ideally I would like to print the response of the webpage in a <div> while still on the same parent web page rather than going to a new one if this is possible.
I have no idea where to begin with this, how to do it or even if this is possible. Can anyone help me please ?
UPDATE :
Trying this JQuery which does not alert me so I cannot debug :
<script>
$("#thebutton").click(function() {
var form = $(document.getElementById('FormID'));
var urlToConstruct = 'http://webaddress.com/web/d.php';
urlToConstruct += '?u=' + form.find('#u').val();
urlToConstruct += '&p=' + form.find('#p').val();
('#employeeTable tbody tr').has(':checkbox:checked').find('td:eq(2)').each(function() {
urlToConstruct.append($(this).text());
alert(urlToConstruct);
})
});
</script>
$("#SubmitButtonID").click(function() {
var form = $(document.getElementById('FormID');
var urlToConstruct = 'http://webaddress.com/web/d.php';
urlToConstruct += '?u=' + form.find('#iDoFInputControl1').val();
urlToConstruct += '&p=' + form.find('#iDoFInputControl2').val();
form.submit();
});
this example uses jQuery, a javascript library (jquery.com), i'm using getElementById to find your form, faster then the native jQuery() selector. This example assumes all your controls are inside your form (but if they are not it wouldn't be a train smash, just cant use (jQuery obj).find).
.val() gets the value, and it should work for checkboxes too, but if it doesn't, a quick google search for getting values from checkboxes using jquery will return loads of results.
p.s. I've written that code mostly freehand, not checked it in a browser to make sure that it is completely correct.
Update... to answer your follow up question...
If you are using mvc (assumed as you using razor), inside your controller you can use Request.Params["urlParameter"] or Request.Form["controlID"] to access what you've received from the browser. Then once you've got those values, you should place them inside the 'ViewBag' (ViewBag.yourVariableHere="val") for them to be accessible in your view via #ViewBag.yourVariableHere, or you can include the required data in your model which can also be accessed in your view

how to invoke a jsp method onclick/on form submit

I have a jsp page with this code:
<script type="text/javascript">
function getWithdrawAmmount()
{
var withdraw=document.forms["WithdrawDeposit"]["AmountToWithdraw"].value;
document.getElementById('hidden').type = withdraw;
}
</script>
<form method="POST" name="WithdrawDeposit" onsubmit="getWithdrawAmmount()">
<table>
<tr><td><input type="text" size=5 name="AmountToWithdraw"></td>
<td><input type="button" value="Withdraw"></td></tr>
</table>
</form>
<input type="hidden" name="hidden" value="">
<% String AmountWithdraw = request.getParameter("hidden"); %>
<%!
public void Withdraw(){
int Amount = Integer.parseInt("AmountWithdraw");
Deposit deposit = new Deposit();
deposit.WithdrawMoney(AmountWithdraw);
} %>
I need to activate the Withdraw() method on form submit and get the text input.
the javascript hold the value inserted in 'hidden' and i can access it later.
but i can't call to : <% Withdraw(); %> from inside javascript.
how can i call Withdraw() after button click?
10x
First off your line of code has issues
document.getElementById('hidden').type = withdraw;
It is looking for an element with an id of hidden. Not a name, an id. So add an id to the element you are referencing.
Second you are setting a type. Don't you want to set the value?
So the HTML would look like
<input type="hidden" name="hidden" id="hidden" value="" />
and the JavaScript would be
document.getElementById('hidden').value = withdraw;
Now if you want to call a function on the server, you either need to post back the form or make an Ajax call.

Categories