473,419 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,419 software developers and data experts.

JSP - Onchange Event - Logic problems refreshing selection

108 100+
Greetings,

I'm slowly building up code to do the following:-
  • Display TWO selection option boxes (cascading).
  • If the FIRST selection option box changes then reload the jsp using onchange event (not changing the option box value on relaod i.e. not re-running the SQL query).
  • ONLY on initial entry should the form FIRST selection option box should be populated using JDBC SQL.
  • The SECOND selection option box can then be populated from the value of the FIRST selection option box.
  • Then when the selection is made from the SECOND selection option box display the correspong record details

My code was attempting to check the value of the option box and if it was null i.e. the first time the user had entered the screen then populate the Option value ELSE just forward its current Value which could be picked up by the SECOND selection box.

However I dont know how to check the Option value as I get the following error message:-

An error occurred at line: 12 in the jsp file: /examples/wk465682UserMenu.jsp
Generated servlet error:
The method getparameter(String) is undefined for the type HttpServletRequest

An error occurred at line: 12 in the jsp file: /examples/wk465682UserMenu.jsp
Generated servlet error:
OptionCategoryValue cannot be resolved

Expand|Select|Wrap|Line Numbers
  1. <!-- the % tag below is what is called a scriptlet tag - allows java to be embedded in the jsp -->
  2. <%@ page import="java.util.*" %>
  3. <%@ page language="java" %>
  4. <%@ page import="java.sql.*" %>
  5. <HTML>
  6. <H1>FAQ</H1>
  7. <% String  OptionCategory = null;%>
  8. <H3>Please choose a category</H3>
  9.  
  10. <FORM ACTION="wk465682UserMenu.jsp" METHOD="POST">
  11. <SELECT NAME="category" onChange="location.href='wk465682UserMenu.jsp?option='+this.value;">
  12.         <% 
  13.  
  14.             Connection conn = null, conn1 = null, conn2 = null;
  15.  
  16.             if (request.getparameter("OptionCategoryValue") == null)     
  17.             {                            
  18.                 try 
  19.                     {
  20.                         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  21.                         conn1 = DriverManager.getConnection("jdbc:odbc:FAQ"); 
  22.                     }
  23.                         catch (Exception e1)  {System.out.print(e1);}
  24.                     {
  25.                         try
  26.                             {  
  27.                                 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  28.                                 conn2 = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver*.mdb)};DBQ=C:/ProgramFiles/Apache Software Foundation/Tomcat 6.0/webapps/2008-sem2/wk465682/FAQ.mdb");        
  29.                             }
  30.                                 catch (Exception e2) {System.out.print(e2);}
  31.                     }
  32.  
  33.         if(conn1 == null) conn = conn2;
  34.         else conn = conn1;
  35.  
  36.         PreparedStatement mystatement = conn.prepareStatement("SELECT category from category");
  37.         ResultSet result = mystatement.executeQuery();
  38.  
  39.         while(result.next()) { 
  40.                                 OptionCategoryValue=result.getString(1); %>
  41.                                 <OPTION VALUE=OptionCategoryValue><%out.println(OptionCategory);%></OPTION>
  42.                             <%}
  43.         } %>
  44.  
  45.     </SELECT>
  46. </FORM>
  47. </HTML>
Mar 15 '08 #1
7 14442
robtyketto
108 100+
Expand|Select|Wrap|Line Numbers
  1.  if (request.getparameter("OptionCategoryValue") == null) 
should be getParameter

Now I get error message :-

An error occurred at line: 12 in the jsp file: /examples/wk465682UserMenu.jsp
Generated servlet error:
OptionCategoryValue cannot be resolved
Can any assist or offer advice, is it clear what I want to achieve overall?
Mar 16 '08 #2
chaarmann
785 Expert 512MB
Expand|Select|Wrap|Line Numbers
  1.  if (request.getparameter("OptionCategoryValue") == null) 
should be getParameter

Now I get error message :-



Can any assist or offer advice, is it clear what I want to achieve overall?
Yessir!

The error you get is because you used a new variable "OptionCategoryValue" and did not define it. You should change it to "String optionCategoryValue".
Please notice that I changed your variable name, starting with capital letter "O" to lowercase letter "o", see the java coding standards. Else you get yourself confused if you name it like java classes are named, but it's not a java class.

Second, what you code trying to achieve is: only reading the values from the database table and put it out as JSP. It doesn't do anything described in your list on top. So how comes? I mean you probably would not have listed these points which have nothing to do with the source code you listed if you don't need some help in that, too? Ok, here it goes:

First, load the data for your first option box only and keep the second option box empty. Then in an OnChange-event on the first option box, make an AJAX-request to load the data for the second option box and display it. Look for "prototype.js" in the internet, it will help you much for the AJAX functions.

By the way, if the data for all the options inside the boxes is very small (let's say less than 20000 characters), I would not "dynamically reload" it. You can just put all the data in one two-dimensional string array, and dynamically rebuild your second option box from there with clientside javascript.
Mar 16 '08 #3
robtyketto
108 100+
Thanks for the reply I've fixed the code errors.

The code offers very little functionality at the moment as Im trying to build it up piece by piece so I can understand whats going on.

I was advised that the OnChange event would pass in the users selection and not re-populate the Option box.

I didnt see how this would work as I thought the Onchange would simply run all of the JSP again, Is this the case ??

Unfortunately I have been advised against using AJAX, without going into too much detail Im a university student and the module lecturer doesnt want any AJAX code (I dont think they will be able to understand it!!)


Expand|Select|Wrap|Line Numbers
  1. <!-- the % tag below is what is called a scriptlet tag - allows java to be embedded in the jsp -->
  2. <%@ page import="java.util.*" %>
  3. <%@ page language="java" %>
  4. <%@ page import="java.sql.*" %>
  5. <HTML>
  6. <H1>FAQ</H1>
  7. <% String  OptionCategory = null;%>
  8. <H3>Please choose a category</H3>
  9.  
  10. <FORM ACTION="wk465682UserMenu.jsp" METHOD="POST">
  11. <SELECT NAME="category" onChange="location.href='wk465682UserMenu.jsp?option='+this.value;">
  12.         <% 
  13.  
  14.             Connection conn = null, conn1 = null, conn2 = null;
  15.  
  16.             if (request.getParameter("OptionCategoryValue") == null)     
  17.             {                            
  18.                 try 
  19.                     {
  20.                         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  21.                         conn1 = DriverManager.getConnection("jdbc:odbc:FAQ"); 
  22.                     }
  23.                         catch (Exception e1)  {System.out.print(e1);}
  24.                     {
  25.                         try
  26.                             {  
  27.                                 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  28.                                 conn2 = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver*.mdb)};DBQ=C:/ProgramFiles/Apache Software Foundation/Tomcat 6.0/webapps/2008-sem2/wk465682/FAQ.mdb");        
  29.                             }
  30.                                 catch (Exception e2) {System.out.print(e2);}
  31.                     }
  32.  
  33.         if(conn1 == null) conn = conn2;
  34.         else conn = conn1;
  35.  
  36.         PreparedStatement mystatement = conn.prepareStatement("SELECT category from category");
  37.         ResultSet result = mystatement.executeQuery();
  38.  
  39.         while(result.next()) { 
  40.                                 String OptionCategoryValue=result.getString(1); %>
  41.                                 <OPTION VALUE="OptionCategoryValue"><%out.println(OptionCategoryValue);%></OPTION>
  42.                             <%}
  43.         } %>
  44.  
  45.     </SELECT>
  46. </FORM>
  47. </HTML>
Mar 16 '08 #4
chaarmann
785 Expert 512MB
The code offers very little functionality at the moment as Im trying to build it up piece by piece so I can understand whats going on.
It will help you if you try to break down your code into small pieces instead of
doing it all in a big chunk.
For example in your code above, you should separate database logic from HTML logic.
That means you should have one method that returns all the values of your SQL-query in a string-array (or Vector of strings). This method should have a parameter that defines for which option box it should load the data.
Then you should have a second method where you pass the string-array, and it will return the HTML-code for the option box.
Then you should write a main method which calls these 2 other methods repeatedly. Like here:

Expand|Select|Wrap|Line Numbers
  1. String categoryArray[] = getOptionBoxData(categoryName);
  2. String categoryHtml = getHtmlCode(categoryArray);
  3. String subcategoryArray[] = getOptionBoxData(subcategoryName);
  4. String subcategoryHtml = getHtmlCode(subcategoryArray);
  5. out.print("please select category:");
  6. out.print(categoryHtml);
  7. out.print("<BR>\nplease select subcategory:");
  8. out.print(subcategoryHtml);
I hope you get the idea. If you start with this setup, you will be successful and ease your work.

I was advised that the OnChange event would pass in the users selection and not re-populate the Option box.
If you are not allowed to use Ajax or frames, you must always transmit the whole webpage which contains the 2 boxes, so you must always transmit the data for both boxes. If your teacher says, not to read the first option box data again from the database, then you must cache it. For example you can store the data for the first option box inside a static variable of your class.

I didnt see how this would work as I thought the Onchange would simply run all of the JSP again, Is this the case ??
Yes. You just submit the category and subcategory as variables of your URL request (either in a form or as URL-parameters), and then your JSP would bring back the HTML-code of a completely new page.

Unfortunately I have been advised against using AJAX, without going into too much detail Im a university student and the module lecturer doesnt want any AJAX code (I dont think they will be able to understand it!!)
I don't think so, I guess he thinks it's too difficult to understand for a beginner,that's why he doesn't want you to use it. Maybe you can try with frames then if he allows that: Put the second option box, (the subcategory box) in an <IFRAME> and then refresh this frame via javascript.
Footnote:
The method your teacher suggests and the "frame"-method are very old. They were used widely when clientside javascript and Ajax were not available in browsers. In the industry, nobody is developing this way anymore. I mean, for learning purposes, you should do what your teacher says. But if you have a job later on as a programmer, you should always use Ajax (if it's a large amount of data. Or if it's a small amount of data, maybe less than 20KB, load all the data inside an array only once, and dynamically recreate the second option box). The advantage of this is much less load for the server and a much faster navigation for the user.
So if you have some more time to spend after doing your task, you should try Ajax of your own, it's really worth it!
Mar 17 '08 #5
chaarmann
785 Expert 512MB
Please notice that I changed your variable name, starting with capital letter "O" to lowercase letter "o", see the java coding standards. Else you get yourself confused if you name it like java classes are named, but it's not a java class.
You did not take my advice. The name in your new code listing is not changed. Why?
I have 28 years experience of programming, and I tell you it's worth doing it, even if it looks unimportant! In general, code is reviewed by other programmers that come after you very often. Very often means roughly 10 to 100 times. If you don't stick to coding standards, you are wasting their time. So get used to it. Let me give you an example to understand the principle:
Let's say you have a cat and you call it "Dog" or "Doggy". If you now go on the street and call "Doggy come here!", everybody would expect a small dog to show up!
So just use the right naming conventions for classes and instance of classes, and your teacher and every programmer who reads your code to help you would be pleased!
Mar 17 '08 #6
robtyketto
108 100+
You did not take my advice. The name in your new code listing is not changed. Why?
I have 28 years experience of programming, and I tell you it's worth doing it, even if it looks unimportant! In general, code is reviewed by other programmers that come after you very often. Very often means roughly 10 to 100 times. If you don't stick to coding standards, you are wasting their time. So get used to it. Let me give you an example to understand the principle:
Let's say you have a cat and you call it "Dog" or "Doggy". If you now go on the street and call "Doggy come here!", everybody would expect a small dog to show up!
So just use the right naming conventions for classes and instance of classes, and your teacher and every programmer who reads your code to help you would be pleased!
Ok Ok I now have all my jsp working.

I will now take the time to add appropriate comments, naming and formatting conventions.

Deadlines for uni meant I had to cut corners, but now I have time to sit down and properly review my code.

Your advice hasn.t fallen on deaf ears.

Thanks
Rob
Mar 17 '08 #7
chaarmann
785 Expert 512MB
Ok Ok I now have all my jsp working.

I will now take the time to add appropriate comments, naming and formatting conventions.

Deadlines for uni meant I had to cut corners, but now I have time to sit down and properly review my code.

Your advice hasn.t fallen on deaf ears.

Thanks
Rob
I am happy to hear that everything runs fine.
Sorry, I got a little excited about naming conventions. To my excuse I can only say that I experienced a lot of cases where wrong naming caused a lot of trouble. Just recently for example a new programmer used a variable name in his JSP page that exactly matched an existing class name. Then we needed to replace this class everywhere with a new improved class. But we have hundreds of files at work, so we used an automatic "replace every occurrence of the old class name with the new name, in all files". So also his variable got replaced. Unfortunately, the source code of a JSP page is only compiled when it is used, so we did not detect the error at once. But instead we got feedback of hundreds of angry users whose webpages were crashing and we had a *nice* debugging session during the night on the weekend until we found the error.
Mar 22 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Paul Eghbal | last post by:
Hi all, I'm trying to use the following script: <script language="javaScript"> function setrepto(){ document.aForm.repno.value = document.aForm.rep.options.value; } </script>
1
by: dan baker | last post by:
I am pretty much a newbie with javascript, and would like to get a little clarification on what I can do with an onChange javascript event handler. I have a dynamic page I build with perl and...
7
by: lawrence | last post by:
Can I do something like the following to get a browser to redirect to a new url every time someone picks a new value in a select box? function changeUrl() { var redirect; redirect =...
4
by: Bart van Deenen | last post by:
Hi all I have a script where I dynamically create multiple inputs and selects from a script. The inputs and selects must have an associated onchange handler. I have the script working fine on...
5
by: doc | last post by:
Hi, <SCRIPT LANGUAGE="JavaScript"> function check_selection(selection){ document.pr.n_o.checked=true; } </SCRIPT> <form name=pr action=test.php method=post>
4
by: Zeebra3 | last post by:
Here goes: I have a web form with several asp:dropdownlists, with which, when selection is changed I want to fire an event defined in some clientside js. The content of the clientside code is...
18
by: Mike Will via WebmasterKB.com | last post by:
I need some help with an onchange event for one of my select boxes on my form. I need to select a value from the box and use that value in the query that will produce results for another select...
21
by: Leena P | last post by:
i want to basically take some information for the product and let the user enter the the material required to make this product 1.first page test.php which takes product code and displays...
8
by: jrayjr | last post by:
Im work on a form that will dynamicly display objects. The form is completed and working but am adding some features that will appear based on the user selection. I am unable to get the onchange...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.