JSP and JavaScript with form - javascript

I have a form in a Registeration.jsp page:
form name="users" method="post" onSubmit="return checkCorrect()"
action="Registeration.jsp">
The Script checkCorrect is written at the start of the page, returns true or false based on information submitted to the form (using getElementById if it matters) and the script definitely works (worked on html page without jsp before)
after the form I have this:
<% if(request.getMethod().equals("POST")){...}
And I need that the jsp part will work ONLY if and after the form is successfully submitted, but somehow the javascript script is not called and don't work and the form is always submitted.
What am I doing wrong?
edits:
there's no redirection in my page, the javascript check function, the form, and the JSP part that procces the form after submitting it are at the same page.
the jsp part is used to send the data from the form to a database.
the function:
function checkCorrect(){
var fullname=document.getElementById("fullname").value;
...
if (response.length==0)
{
return true;
}
else
{
alert ("These problems are found in your form:\n\n"+response);
return false;
}
}
then come the body and the form and then
the jsp part:
<%
if(request.getMethod().equals("POST")){
String fullname=request.getParameter("fullname");
and go on.. } % >
Solution:
check the JavaScript part really good people it doesn't have compiler so even a tiny problem there can screw up the entire project.

<% uname=""+request.getAttribute("username"); %>
This variable will get a value only when you load your page or refresh it.
I guess your page flow is as follows.
You have your first page with form, and onsubmit form will call javascript function as
<form name="users" method="post" onSubmit="returncheckCorrect()" action="Registeration.jsp">
then your javascript will check your answer like :
<script type="text/javascript">
function returncheckCorrect() {
var x = document.getElementsByName("userName")
if (your condition) {
alert("Redirecting");
return true;
} else {
alert("Not Redirecting");
return false;
}
}
// return false; // lol, see why indentation is useful ?
</script>
then (if (your condition == true)) your java script will redirect to a second page where you want to get the value in a scriptlet like
<% uname=""+request.getAttribute("username"); %>
Make sure your code is in this manner.
Following is the code which I tried as you said, its working
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
function chkme() {
var x = document.getElementById('textfield');
if (x.value == 'sarin') {
alert("success");
} else {
alert("failed");
}
return true;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form id="form1" name="form1" method="post" onsubmit="chkme();"
action="">
<input type="text" name="textfield" id="textfield" /> <input
type="text" name="textfield2" id="textfield2" /> <input
type="submit" name="button" id="button" value="Submit" />
</form>
<%
if (request.getMethod().equals("POST")) {
String textfield = request.getParameter("textfield");
String textfield2 = request.getParameter("textfield2");
%>
<%=textfield%>
<br />
<%=textfield2%>
<%
}
%>
</body>
</html>

Related

passing variable without button onclick event

I am getting null value in variable k can anyone help me plz ..... It is taking the input of alert but not setting value to k can I perform the same without button or click event
<% // some jsp code
String key="some value";
if(key!= null)
{
%>
<html>
<head>
<script type="text/javascript">
var val = prompt("Please enter R for Read or W for Write", "");
document.getElementById("hid").value=val;
</script>
</head>
<body>
<input type="hidden" id="hid" name="hid" />
</body>
</html>
<%
}
String k=request.getParameter("hid");
key=key+k;
System.out.println(key);
%>
Just add a window.onload event handler
<% // some jsp code
String key="some value";
if(key!= null)
{
%>
<html>
<head>
<script type="text/javascript">
var val = prompt("Please enter R for Read or W for Write", "");
window.onload = function() {document.getElementById("hid").value=val; }
</script>
</head>
<body>
<input type="hidden" id="hid" name="hid" />
</body>
</html>
<%
}
String k=request.getParameter("hid");
key=key+k;
System.out.println(key);
%>
The Javascript is executing before the DOM is loaded, try either putting the code before the script (put script at base of body as recommended), or as stated use window.onload or jQuery $(function(){});

Validate Captcha in JSP Page using AJAX

Trying to Use Captcha in my JSP page as below
<%# page import="net.tanesha.recaptcha.ReCaptcha" %>
<%# page import="net.tanesha.recaptcha.ReCaptchaFactory" %>
<html>
<head>
<title>Sample Application JSP Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body bgcolor=white>
<form action="CaptchaServlet">
<table border="0" cellpadding="10">
<tr>
<td width="10" align="center" height="10">
<img src="SimpleServletPath">
</td>
<td>
<h1>Sample Application JSP Page</h1>
</td>
</tr>
<tr>
<td>
Please Enter your Comments
<p>
<%
ReCaptcha c = ReCaptchaFactory.newReCaptcha
("6LdlHOsSAAAAAM8ypy8W2KXvgMtY2dFsiQT3HVq- ", "6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY", false);
out.print(c.createRecaptchaHtml(null, null));
%>
<INPUT TYPE="TEXT" NAME="text1">
<input type="submit" value="submit" />
</p>
</td>
</tr>
</table>
</form>
</body>
</html>
The servlet is as follows
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String remoteAddr = request.getRemoteAddr();
ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey("6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY");
String challenge = request.getParameter("recaptcha_challenge_field");
String uresponse = request.getParameter("recaptcha_response_field");
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
PrintWriter out= response.getWriter();
if (reCaptchaResponse.isValid()) {
String user = request.getParameter("user");
out.write("CAPTCHA Validation Success! User "+user+" registered.");
} else {
out.write("CAPTCHA Validation Failed! Try Again.");
}
}
This works good, but the JSP page gets refreshed when submit value is clicked. How can we pass the Captcha values to Servlet using AJAX and return a value that the Capcha is valid or not without refreshing the page.
Here is the strategy.
Have your submit tracked by a javascript method. That method will send the captcha data to the server. and on sucesss or error the javascript will update the dom with the error message sent by the server/Servlet.
Follow this link https://gist.github.com/madan712/4972634.
In the link above it uses another jsp to validate ( working like a servlet) but you can give the url mapping name there in the url:[your_servlet_path]

redirecting to controller class from popup window

I am using Spring controller, jsp as view with javascript and html as front end view. I have popup window, When I submit the button, it should redirect to controller class.
JavaScript code with html:
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
loginQB = function(){
var win = window.open('about:blank', 'popup', 'width=640,height=580,resizeable,scrollbars');
<!-- win.document.write('<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>');
win.document.write('<form:form id="qblogin" method="POST" action="/asi/mappings">');--!>
win.document.write('<br>Sign in with Intuit Account or CreateOne');
win.document.write('<br><input type="text" name="userName">');
win.document.write('<br><input type="password" name="password">');
win.document.write('<br><input type="submit" value="Submit">');
<!--win.document.write('</form>');-->
}
</script>
</head>
<body>
<form:form id="qblogin" method="POST" onsubmit="loginQB(); return false;">
<select name="quickbooks" id="qb" >
<option value="qb-1">Books Desktop</option>
</select>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
Spring controller class:
#Controller
#SessionAttributes("mappingSession")
public class MappingsController {
#RequestMapping(value="/mappings", method = RequestMethod.POST)
public String dataMappings(Model model) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
First of all, why don't you use Bootstrap Modal for your pop up.
http://getbootstrap.com/javascript/#modals
Secondly, when you submit, you can get the information from your form, serialize it and then pass it to the controller.
http://api.jquery.com/serialize/
I strongly recommend you to change the implementation of your popup.

send command to server after click in a checkbox

I am developing a application where I have a jsp page with a dynamicly generated table (which is made using jstl) where each cell have one checkbox. When I mark this checkbox, I need that an event be triggered to database to insert an row in a table. If I unmark the checkbox, this row should br removed. Someone have any idea how to do this? My thoughts about this is that I should use some ajax code for this, but I have no clue by where start. Someone can give me some ideas about this (don't even need code, an sort of algorithm should be enough, I guess).
I follow the suggestion from Mr Matej Chrenko, and write the follow code:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="jquery-1.11.0.min.js"> </script>
<script>
$(".checkbox").change(function() {
if(this.checked) {
window.alert("unmarked");
} else{
window.alert("marked");
}
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cadastra Horario Livre</title>
</head>
<body>
<p align="center">
<span class="usuario">${nome}</span> | <strong> Hora Livre</strong> | Sair
</p>
<p align="center">
<form method="post" action="">
<table border = 2>
<tr>
<th> </th>
<c:forEach var="item" items="${list2}">
<th> <c:out value="${item}"/> </th>
</c:forEach>
</tr>
<c:forEach var="item2" items="${list}">
<tr>
<td> <c:out value="${item2}"/> </td>
<c:forEach var="item" items="${list2}">
<td> <input type="checkbox"> </td>
</c:forEach>
</tr>
</c:forEach>
</table>
</form>
</p>
</body>
</html>
However, nothing is happening when I click on the checkbox. What I did wrong? (I add the jquery file inside the folder WEB-INF of my project - same place this jsp is located).
This:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
} else{
//unchecked
}
});
and this:
https://api.jquery.com/jQuery.ajax/
would help you.
I think Ajax is the possible solution. You can use jQuery to do it easier.
You can refer here
Ok, I solve the problem by changing the javascript code used to sent the request to the server. I follow the instructions from this article.
The code for the JSP page ended like that:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="<c:url value='/js/ajax.js'/>"></script>
<script>
function handleClick(cb, idevento, data, hora) {
if(cb.checked) {
alert("marked "+data+" "+hora+" for "+idevento);
sendAjaxRequest("/hora_livre/CadastraHoraLivre?target=cadastra&data="+data+"&hora="+hora+"&evento="+idevento, "showdetails");
} else{
alert("unmarked "+data+" "+hora+" for "+idevento);
sendAjaxRequest("/hora_livre/CadastraHoraLivre?target=remove&data="+data+"&hora="+hora+"&evento="+idevento, "showdetails");
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cadastra Horario Livre</title>
</head>
<body>
<p align="center">
<span class="usuario">${nome}</span> | <strong> Hora Livre</strong> | Sair
</p>
<p align="center">
<table border = 2>
<tr>
<th> </th>
<c:forEach var="item" items="${list2}">
<th> <c:out value="${item}"/> </th>
</c:forEach>
</tr>
<c:forEach var="item2" items="${list}">
<tr>
<td> <c:out value="${item2}"/> </td>
<c:forEach var="item" items="${list2}">
<td> <input type="checkbox" id="checkbox" onclick="handleClick(this, '${id}', '${item2}', '${item}')"> </td>
</c:forEach>
</tr>
</c:forEach>
</table>
<div id="showdetails"> </div>
</p>
</body>
</html>
the file ajax.js included in the page is that:
/* common method to get XMLHttp request object */
function getXMLHttpRequest() {
var req;
if (window.XMLHttpRequest) { // For Firefox, Mozilla, Safari, …
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // For IE
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
//
}
}
}
return req;
}
/* method for dynamically getting current time in milliseconds and append that value to no-cache parameter
* IE browser does not send ajax request if the url is same, simply get result from cache
* to avoid this and make a new request, we append no-cache param to each ajax request.
*/
function getNoCacheValue(url)
{
var d = new Date();
var appendstring = (url.indexOf("?") != -1) ? "&" : "?";
var nocachevalue = appendstring + "no-cache=" + d.getTime();
return nocachevalue
}
/* method to send a ajax request, and write the response text to given divid. */
function sendAjaxRequest(url, divid) {
url = url + getNoCacheValue(url);
var req = getXMLHttpRequest();
req.onreadystatechange = function() {
processResponse(req, divid)
};
req.open('GET', url, true);
req.send(null);
}
function processResponse(req, divid) {
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById(divid).innerHTML=req.responseText;
invokeScript(document.getElementById(divid));
}
}
}
/* method for executing script separately.
* (scenario : send a Ajax request, response is HTML with some scripts – scripts in response HTML should not load )
* to overcome this issue, we used this method to load the scripts separately.
*/
function invokeScript(divid) {
var scriptObj = divid.getElementsByTagName("SCRIPT");
var len = scriptObj.length;
for(var i=0; i<len; i++) {
var scriptText = scriptObj[i].text;
var scriptFile = scriptObj[i].src
var scriptTag = document.createElement("SCRIPT");
if ((scriptFile != null) && (scriptFile != "")) {
scriptTag.src = scriptFile;
}
scriptTag.text = scriptText;
if (!document.getElementsByTagName("HEAD")[0]) {
document.createElement("HEAD").appendChild(scriptTag)
}
else {
document.getElementsByTagName("HEAD")[0].appendChild(scriptTag);
}
}
}

How to implement an "Auto Save" or "Save Draft" feature in ASP.NET?

I have a registration form in ASP.NET 2.0. I want to save my registration form fields either by clicking on submit button or they should be saved every five seconds.
For example I have three fields in my registration page:
UID
PWD
Name
The user has entered UID and PWD and whilst he is entering Name the previous values should be saved without interruption of user inputs
How would I do this in ASP.NET?
You could do this with a snippet of Javascript & jQuery. Have a function that's fired by a timer that periodically reads the form data you want to save and posts it back to a SaveDraft.aspx page. In this page persists the data somewhere (such as a database).
If the user logs out or their session is lost you can query for this data and pre-populate the form if the data exists.
On your data entry ASPX page:
// Usual ASP.NET page directives go here
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js" ></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:textbox id="username" runat="server" /><br />
<asp:textbox id="password" runat="server" /><br />
<asp:textbox id="realName" runat="server" /><br />
<asp:button id="Submit" onclick="Submit_Click"
usesubmitbehavior="true" runat="server" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
// Configure to save every 5 seconds
window.setInterval(saveDraft, 5000);
});
// The magic happens here...
function saveDraft() {
$.ajax({
type: "POST",
url: "SaveDraft.aspx",
data: ({
username: $("#<%=username.ClientID %>").val(),
password: $("#<%=password.ClientID %>").val(),
realName: $("#<%=realName.ClientID %>").val()
}),
success: function (response) {
alert('saved draft');
}
});
}
</script>
</body>
</html>
In your SaveDraft.aspx page:
public partial class SaveDraft : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = Request.Form["username"];
string password = Request.Form["password"];
string realName = Request.Form["realName"];
// Save data somewhere at this point
}
}
That should get you started.

Categories