Hi.
i'm new user of jsp and i have this problem.
I post my code

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="it.yacme.mystiquexml.mapping.Modello"%>
<%@ page import="it.yacme.mystiquexml.mapping.*" %>
<%@ page import="it.yacme.mystiquexml.business.YacmeRemote"%>
<%@ page import="it.yacme.mystiquexml.presentation.YacmeLocator"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.StringTokenizer"%>

<%!	
	String jndiURL = null; 
	public void jspInit() {
		jndiURL = (String)getServletConfig().getInitParameter("mystique.server.jndi.url");
	}
%>
<%
	YacmeRemote ccb = null;
	try {
		ccb = YacmeLocator.bind(jndiURL);
	} catch (Exception e) {}
	
%>


<html>
<head>
<!--<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  -->
<META HTTP-EQUIV = "pragma" CONTENT="no-cache">
<title>Demo MyStique</title>
<script type="text/javascript" language="JavaScript"> 
       function crea(valore,identificatore){
            nuovo_elemento = document.createElement("div");
            now= valore;
            nuovo_elemento.innerHTML=now.toLocaleString();
            document.getElementById("container").appendChild(nuovo_elemento);
            obj=eval("document.getElementById(\"quadro"+parseInt(document.getElementById("container").childNodes.length)+"\")");
 		
            idArticolo= identificatore;
            
            }
            
         function mostraID(){
         alert(idArticolo);
         } 
        </script>
</head>
<body>
<center>
<table>
	<tr>
		<th class="title">Demo MyStiqueXML</th>
	</tr>
</table>
<p /><br />
<form action="../pages/maschera.jsp" id="form01" method="post">
<h1>Scegli il tipo di documento che vuoi creare</h1>
<legend>
<h4>Tipi di documento</h4>
</legend>
<select id="modelli" name="modelli"
	onChange="crea(this.options[this.selectedIndex].value,this.options[this.selectedIndex].id)">
	<%
		List articoli = ccb.listArticolo();
        for (Iterator<Articolo> iter = articoli.iterator(); iter.hasNext();) {
        	Articolo articolo = iter.next();
	%>
			<option id="<%=articolo.getId_articolo()%>" value="<%=articolo.getDescrizione_articolo()%>"><%=articolo.getNome_articolo()%></option>
		
			
	<%
		}
	%>
</select>
 <div class="container" id="container"/>
<br />
<input type="submit" value="Avanti" onClick="mostraID()"/>
</form>
</body>
</html>

I want save me the value of javascript varible "idArticolo" in a jsp variable if it is possible.
if isn't possible how can i do to save me that value to send to the next page?

Thank you

Dani AI

Generated

Short answer: you cannot directly assign a client-side JavaScript variable to a JSP variable in the same page. JSP runs on the server and emits HTML before any browser JavaScript executes. To get a value from the browser back to the server you must make another request (form submit, AJAX/fetch, URL query, or cookie). The hidden-field suggestion from is the simplest and most usual approach for form-based flows.

Practical checklist to make that work reliably:

  • Put a form field with a name inside the form so the browser will submit it. Set that field when the user selects the option (your existing selection handler is the right place to update it). Make sure you update the field before the form actually submits (attach an onsubmit handler on the form if you need to guarantee timing).
  • On the receiving JSP/servlet read the submitted value from the request and proceed. Do not expect a server-side variable to change without a new request/response cycle.

Specific troubleshooting for the code you posted ():

  • A self-closing DIV will break DOM operations in HTML4/Transitional. Ensure the container element is a normal element (not self-closed) so appendChild works.
  • Declare your JavaScript variables (use var/let/const). Assigning to an undeclared identifier creates globals and makes bugs harder to trace.
  • Avoid eval and fragile childNodes counts; prefer DOM methods and element children lists.
  • If you choose to put the value into the action URL, remember to encode it properly.

Alternatives and cautions:

  • If you need the value server-side without a full form submit, send it via AJAX to a servlet that stores it in session or returns a redirect. Or set a cookie and read it on the next request.
  • Never trust client-side data: always validate and sanitize on the server. Also consider moving logic out of JSP scriptlets into a controller + JSTL/EL for cleaner, maintainable code.

Keep a hidden field which would carry the content of the variable idArticolo to the next page which can be then retrieved using the getParameter method of the HttpServletRequest object.

<!-- In your HTML -->
<form action="/someServlet" id="frm"
  <input type="hidden" name="hid" id="hid" value="default">
</form>
// In your javascript
function crea(valore,identificatore) {
  // All the other stuff goes here
  var hiddenElem = document.getElementById("hid");
  if(hiddenElem) hiddenElem.value = identificatore;
}

Just make sure that the crea() function gets called before the form is submitted. You can also assign a default value to the hidden field so that at the server you can determine whether that field was set or not.

Oh and BTW, using scriptlets is bad. There are better ways of dynamically writing out content like JSTL / JSF / some framework which ensure the separation of content / presentation / logic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.