send command to server after click in a checkbox - javascript

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);
}
}
}

Related

Why return 404 error? javascript to refresh div

I'm trying to insert a script to make a div refresh with javascript/ajax. I found the following code.
I don't put prova.asp page because it contains only a response.write "Hello" (then I will modify with database query).
This code returns a 404 error and I do not understand why. The only URL is prova.asp and this file is in the same folder.
Anyone can tell me where I'm wrong? the mistake is mine but I don't know what it is.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
//If our user enters data in the username input, then we need to enable our button
function OnChangedUsername(){
if(document.form1.newuserid.value == ""){
document.form1.btnCheckAvailability.disabled = true;
}
else
{
document.form1.btnCheckAvailability.disabled = false;
}
}
function OnCheckAvailability(){
if(window.XMLHttpRequest){
oRequest = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
oRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
oRequest.open("POST", "prova.asp", true);
oRequest.onreadystatechange = UpdateCheckAvailability;
oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.send("strCmd=availability&strUsername=" + document.form1.newuserid.value);
}
function UpdateCheckAvailability(){
if(oRequest.readyState == 4){
if(oRequest.status == 200){
document.getElementById("Available").innerHTML = oRequest.responseText;
}
else
{
document.getElementById("Available").innerHTML = "Asynchronous Error";
}
}
}
</script>
</head>
<body>
<form method="post" action="javascript:void(0);" name="form1">
<table cellspacing="0">
<tr>
<th><label for="newuserid">Username:</label></th>
<td><input type="newuserid" name="newuserid" id="newuserid" size="20" onKeyUp="OnChangedUsername();"/></td>
<td><input id="btnCheckAvailability" type="button" disabled="disabled" value="Check Availability" onClick="OnCheckAvailability();"></td>
<td><div id="Available"></div></td>
</tr>
</table>
</form>
</body>
</html>
Maybe, the browser try to first execute the script.
Add your script before closing div tag.
<body>
...
...
<script .... >
.....
</script>
</body>
Or try to add defer
<body>
...
...
<script .... defer>
.....
</script>
</body>
Or async
<body>
...
...
<script .... async >
.....
</script>
</body>

AJAX hidden call jsp page

i have my index.jsp :
<%# page pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8"/>
<title>Hello</title>
</head>
<body>
Hello !
<input type="hidden" name="ip" value="" id="ip">
<script>
var ip = document.getElementById("ip");
ip.value = userip;
</script>
</body>
</html>
I have another view.jsp which one take an argument like that :
http://localhost:8200/view/view.jsp?ip=IP_VALUE
Then when i open this link and replace IP_VALUE by anything, this value is automatically added to my database.
But now i'm trying to call hiddenly this jsp page, i mean i want that when the user open my page, my javascript variable "ip" is past to my view.jsp like :
http://localhost:8200/view/view.jsp?ip= "ip"
But i want that the user don't see that, so i don't want any redirection or form, just an AJAX hidden call of my jsp.
view.jsp is on the same folder than my index.jsp
How can i do that hiddenly ?
Try this:
<%# page pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8"/>
<title>Hello</title>
</head>
<body>
Hello !
<input type="hidden" name="ip" value="" id="ip">
<script>
var ip = document.getElementById("ip");
ip.value = userip;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'view.jsp?ip' + userip, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
//alert(xmlhttp.responseText);
}
}
};
xmlhttp.send(null);
</script>
</body>
</html>
You can send any value to any page by XMLHttpRequest object.

Calling a Stateful bean action that returns a JSF view Id in a loop to render PDFs

Is there a way to call a Stateful Bean action that renders a PDF using JSF more than once (in a loop)? I tried doing it via Javascript where I invoke a .click() event on each button I created for each PDF job I'd like to render. The xhtml looks like the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:a="http://richfaces.org/a4j"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:rich="http://richfaces.org/rich">
<ui:composition>
<div id="dataSizingDivGrowth">
<f:subview id="fbiAdminId" rendered="#{user.FBIAdmin}">
<h:inputHidden value="#{pdfPrinter.emailsSize}" id="emailSizeId"/>
<h:inputHidden value="#{pdfPrinter.downloadIds}" id="downloadIds"/>
<br />
<table>
<tr>
<td colspan="4" align="center">
<button type="button" onclick="savePDF();">Send Emails</button>
<c:forEach items="#{pdfPrinter.downloadIdsArr}" var="value">
<h:form id="emailAutoForm-#{value}" target="_blank">
<h:inputHidden value="#{pdfPrinter.currDownloadId}" id="currDownloadId-#{value}"/>
<h:commandButton action="#{pdfPrinter.emailAutoCD()}" id="savePDFId-#{value}" style="display:none"/>
</h:form>
</c:forEach>
</td>
</tr>
</table>
</f:subview>
</div>
<script type="text/javascript">
function savePDF() {
//alert("start saving pdf");
var emailSize = document.getElementById("emailAuto:fbiAdminId:emailSizeId").value;
alert("before downloadIdsArr " + emailSize);
var downloadIds = document.getElementById("emailAuto:fbiAdminId:downloadIds").value;
var downloadIdsArr = downloadIds.split("?");
//alert("before getting length");
//alert(downloadIds);
//alert(downloadIdsArr.length);
//alert(downloadIdsArr[0]);
for ( var i = 0; i < emailSize; i++ ) {
var j = function(x) {
document.getElementById("emailAuto:fbiAdminId:emailAutoForm-" + downloadIdsArr[x] + ":currDownloadId-" + downloadIdsArr[x]).value = downloadIdsArr[x];
document.getElementById("emailAuto:fbiAdminId:emailAutoForm-" + downloadIdsArr[x] + ":savePDFId-" + downloadIdsArr[x]).click();
}
j(i);
}
}
</script>
</ui:composition>
</html>
What happens is that the javascript loop only calls the last iteration and executes that and ignores anything before. Any help would be appreciated.

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]

JSP and JavaScript with form

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>

Categories