JQuery - Servlet post fails erratically - java

I am new to JQuery, I am running into a wierd issue here, I try to do a post of my HTML form to a servlet, and try to print data on the servlet. Data gets printed most of the times I submit the form (say 7 times out of 10) with new values. But It fails the other 3 times, I could not find a pattern at which this is failing.
I tried using firebug and chrome tool, I don't see an error on the console, and I get 200 response in the resources/HTML tool in chrome every time I submit the form with correct values set.
Here is my code
HTML
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.16.custom/js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<form id="fcall">
<p> Start Date: <input type="text" name="start" id="ibox_start">
End Date: <input type="text" name="end" id="ibox_end"> </p>
<div id="buttonID">
<input type="submit" value=" Find " class="button"></div>
</form>
main.js
$().ready(
function(){
$('#ibox_start').datepicker();
$('#ibox_end').datepicker();
$('#fcall').submit(
function(){
var start = $('#ibox_start').val();
var end = $('#ibox_end').val();
alert(start);
$.post("DServlet", {start:start,end:end}, function(data) {});
}
);
}
);
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String start = request.getParameter("start");
String end = request.getParameter("end");
System.out.println("Date Recieved "+start);
}

I would expect to see one of the following :
natural HTML form submission
natural HTML form submission with a submit handler which validates form values and returns either true to allow form submission or false to suppress it.
a submit handler that submits form data by AJAX, establishes a .done() handler to handle the HTTP response, and returns false to inhibit natural HTML form submission.
The code above looks like a hybrid of these possibilities.

Related

jsp form send data to servlet without changing page

I use jsp+servlets and have a form. How can I send the form data to a servlet (to the doPost() method) without leaving the actual page, that contains the form?
I want to press the button "submit", the data should be sent and I want to still remain on the page with the form. I would rather not use javascript.
I have on http://localhost/myproject/
<form action="http://localhost/myproject/anotherpage" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
when clicking the submit button i get forwarded to the following page: http://localhost/myproject/anotherpage
but I want to stay on
http://localhost/myproject/
edit: right now I am going to write
request.getRequestDispatcher("/index.jsp").forward(request, response);
in the doPost() method
You should have a form with method="POST" in your JSP
<form method="post">
<input type="number" name="number1" id="number1" />
+
<input type="number" name="number2" id="number2" />
<input type="submit" />
</form>
Then in your servlets, in the doPost method, you have to get the parameters of your form with getParameter("name"), do what you want on it, then resend it to your JSP (setAttribute).
Don't forget to link with your jsp (last line of my example)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String textNumber1 = request.getParameter("number1");
String textNumber2 = request.getParameter("number2");
int number1 = (!textNumber1.isEmpty() ? Integer.parseInt(textNumber1) : 0);
int number2 = (!textNumber2.isEmpty() ? Integer.parseInt(textNumber2) : 0);
int result = number1 + number2;
request.setAttribute("result", Integer.toString(result));
request.setAttribute("number1", Integer.toString(number1));
request.setAttribute("number2", Integer.toString(number2));
this.getServletContext().getRequestDispatcher("/WEB-INF/calc.jsp").forward(request, response);
}
Finally on your JSP, get the attribute from your servlet you want to display on the same page with getAttribute
<%
String number1 = (String) request.getAttribute("number1");
String number2 = (String) request.getAttribute("number2");
String result = (String) request.getAttribute("result");
if (number1 != null && number2 != null && result != null) {
out.print(String.format("<p>Result of %s + %s = <strong>%s</strong></p>", number1, number2, result));
}
%>
This example is a little calculator that show you the result of number1 + number 2 on the same page of the form ;)
I would advise you not to forward to initial page from the second one, but instead to redirect to it in order to follow the Post-Redirect-Get pattern.
If you do not, the user will see in his URL bar the address of the page where he posted data, and if he clicks the back button he will get the ugly message of duplicate post submissions.
So in you doPost() method just to :
response.sendRedirect("/back/to/your/page");
As as alternative, you could hide the JSP page behind the servlet, and have the servlet to directly forward to the JSP page for a GET request, and do its work for a POST and then either forward to the JSP or redirect to itself. In that case, you would not set any action in the <form> tag to have the data posted to same URL.
As it would keep same URL, you could eventually simply do a forward, but I still recommend a redirect to avoid the back button problem.
On you servlet, define the jsp you want to return.
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/path/to/your/jsp");
requestDispatcher.forward(req, res);
If you mean to send data without refreshing current page, you might want to look at sending ajax request.
This doesn't let you stay on the form page, but redirects you back to it right away. And you can of course use the values you just entered.
JSP form
<form method="post" action="yourServlet">
Servlet (in doPost())
getServletContext().getRequestDispatcher("/back/to/your.jsp").forward(request, response);
You can use javascript and ajax (XMLHttpRequest), or specify a target to your form, that references a hidden iframe.

Calling Servlet from JavaScript

I intend to call a function in JavaScript which then calls a Servlet after an <input type="image"> is clicked.
JSP:
<head>
<script type="text/javascript">
function callServlet() {
document.location.href="test-servlet.jsp";
}
</script>
</head>
<body>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
...
<input type="image" name="submit"
src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
onclick="callServlet()" alt="PayPal - The safer, easier way to pay online!">
</form>
</body>
Servlet (test-servlet.jsp):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>TestServlet called successfully!</h1>");
}
Context Root:
http://localhost:8080/mysite/test-servlet.jsp
However, nothing happens when I click the image button. I am new to JavaScript.
Try this code
<a href="#" onclick="callServlet()"><img
src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
alt="PayPal - The safer, easier way to pay online!"></a>
EDIT:
Finally we discovered that a servlet should be mapped without extension and doGet method is used to get the request from javascript.
I Could see multiple errors in your jsp .
First of all ,
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
And also use the img tag with button as Roman says
the url in the action is called , when your form is being submitted
so try replacing it with ,
<form action="./test-servlet" method="post">
and using your JavaScript now,
You cant use window.location.href to make a POST request . check pass post data with window.location.href
<script type="text/javascript">
function callServlet() {
document.forms[0].submit;
}
</script>

Submitting multiple text fields and files in HTML form with AJAX

Im new to AJAX/JQuery, and I'm wondering if there is a way to send, via an AJAX request, data from an HTML form that includes a text file, and 2 separate text boxes. I have been able to send the data from the text boxes, but the file is not sent.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// this is the id of the form
$("#SQLsubmit").submit(function() {
var url = "DAOserv"; // the script where you handle the form input.
$.ajax({
type : "POST",
url : url,
data : $("#SQLsubmit").serialize(), // serializes the form's elements.
success : function(data) {
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
This is my AJAX call^
<div class="row">
<form id="SQLsubmit" name="SQLsubmit">
<div class="form-group col-lg-4">
<textarea rows="11" id="BAU" name="BAU" class="form-control"
placeholder="BAU Reason" form="SQLsubmit"></textarea>
<input type="file" name="file" /> <input type="submit"
class="btn btn-primary" value="Submit">
</div>
<div class="form-group col-lg-8">
<textarea rows="11" id="SQL" name="SQL" class="form-control"
placeholder="SQL Statements" form="SQLsubmit"></textarea>
</div>
</form>
Here is the HTML.
If anyone could show me how to get the two text files, and the file into my Java Servlet (using the doPOST method), so I am able to parse all into strings, that would be greatly appreciated!
Thanks!
edit: The problem I am having when running the code in the original post is that the text fields get sent, but the file is not being sent.
You should define enctype: 'multipart/form-data. Otherwise how jquery should know you are sending a file.
This link might help:
How can I upload files asynchronously?
Have you tried
$("#SQLsubmit").submit(function() {
var url = "DAOserv"; // the script where you handle the form input.
$.ajax({
type : "POST",
url : url,
data : new FormData(this),
success : function(data) {
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

invoking java scriptlet in JSP using HTML

I am trying to find a way to invoke a piece of java code within the JSP using HTML form
<form method="get" action="invokeMe()">
<input type="submit" value="click to submit" />
</form>
<%
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
the above code is within the JSP. I want this run the scriptlet upon submit
I know the code looks very bad, but I just want to grasp the concept... and how to go about it.
thanks
You can use Ajax to submit form to servlet and evaluate java code, but stay on the same window.
<form method="get" action="invokeMe()" id="submit">
<input type="submit" value="click to submit" />
</form>
<script>
$(document).ready(function() {
$("#submit").submit(function(event) {
$.ajax({
type : "POST",
url : "your servlet here(for example: DeleteUser)",
data : "id=" + id,
success : function() {
alert("message");
}
});
$('#submit').submit(); // if you want to submit form
});
});
</script>
Sorry,not possible.
Jsp lies on server side and html plays on client side unless without making a request you cannot do this :)
you cannot write a java method in scriptlet. Because at compilation time code in scriptlet becomes part of service method. Hence method within a method is wrong.
How ever you can write java methods within init tag and can call from scriptlet like below code.
<form method="get" action="">
<input type="submit" value="click to submit" />
</form>
<%
invokeMe();
%>
<%!
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
Not possible.
When the form is submitted, it sends a request to the server. You have 2 options:
Have the server perform the desired action when the it receives the request sent by the form
or
Use Javascript to perform the desired action on the client:
<form name="frm1" action="submit" onsubmit="invokeMe()"
...
</form>
<script>
function invokeMe()
{
alert("He invoked me. I am happy!")
}
</script>
You can't do this since JSP rendering happens on server-side and client would never receive the Java code (ie. the invokeMe() function) in the returned HTML. It wouldn't know what to do with Java code at runtime, anyway!
What's more, <form> tag doesn't invoke functions, it sends an HTTP form to the URL specified in action attribute.

JSP form parameters disappear when I POST my form to another page

If I leave the action attribute out of my form so it posts back to the same JSP I have no trouble reading the request parameters. However when I add an action attribute to handle the form with a separate JSP, the request parameters are null. Here's a short example (FormTest.jsp) that illustrates how I'm reading the request.
<HTML>
<HEAD>
<TITLE>FormTest.jsp</TITLE>
</HEAD>
<BODY>
<H3>Using a Single Form</H3>
<%
String command = request.getParameter("submit");
%>
You clicked <%= command %>
<FORM NAME="form1" METHOD="POST">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="First">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Second">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Third">
</FORM>
</BODY>
</HTML>
The above page works as expected. Initially the page prints You clicked null along with the form. Clicking any of the three buttons changes the message to You clicked First, etc.
Now I change just one line in the page above to add the action attribute:
<FORM NAME="form1" METHOD="POST" ACTION="FormHandler.jsp">
I added a separate JSP to my project to read the request parameter as follows:
<HTML>
<HEAD>
<TITLE>FormHandler.jsp</TITLE>
</HEAD>
<BODY>
<H3>Form Handler</H3>
<%
String command = request.getParameter("submit");
%>
You clicked <%= command %>
</BODY>
</HTML>
I expected the new FormHandler.jsp to just print out which button was pressed on the other page, but it seems the request parameter is always null.
What could be interfering with the request parameters being sent to a separate JSP?
Update:
This project has a JSF configuration file as well. I changed the action attribute to ACTION="FormHandler.faces" and the code above works but I don't quite understand why yet. Here's the method that's redirecting requests that end in .jsp.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String uri = request.getRequestURI();
if (uri.endsWith(".jsp")) {
int length = uri.length();
String newAddress = uri.substring(0, length - 3) + ".faces";
response.sendRedirect(newAddress);
}
else { //Address ended in "/"
response.sendRedirect("login.faces");
}
}
Now I guess I need to know 1) how to figure out if this is the source of the problem, and 2) is there a way to preserve the request parameters when the response is redirected?
There's also an entry in the web.xml configuration file for this project that sets a filter mapping.
<filter-mapping>
<filter-name>faces-redirect-filter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
I suppose (but it's probably clear by now that I'm new to JSF, so someone correct me if I'm wrong) that using the .faces extension in my action attribute bypasses this filter.
POST parameters are lost because sendRedirect() sends a 302 Moved Temporarily redirect, which instructs the browser to load the specified page with GET request.
To retain parameters you need to use 307 Temporary Redirect instead - it instructs the browser to repeat a POST request to the specifed URI:
response.setHeader("Location", newAddress);
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);

Categories