In this posting, I want to explain how I have made use of AJAX in a Struts application
On my current project, I’m building a Struts-based web application with many input forms. Many of these forms contain two or more dependable html select boxes. This means, when you have two dependable boxes, that the available options in the second selectbox depends on the value selected in the first selectbox. To do this there are three possible solutions:
- Use javascript arrays, where each set of options links to an option in the first select-box
- Use an onchange on the first select box to automatically submit the form to go back to the server, collect the new options for the second box and regenerate the whole page
- Use Ajax to asynchronously retrieve the new options for the second box
The first option is not what we wanted: it means that we have to implement a lot of logic in the html-page, which is visible to the outside world and in common javascript isn’t the easiest language to debug
. The second option is better, but has the big disadvantage that you have to do a complete round trip to the server to collect the new options and after that the whole page is regenerated again where actually only the second box is updated..a lot of overhead..
So we decided to use AJAX to solve our problem of dependend select-boxes.
Because Struts does not have AJAX support yet (wait for Shale..) we have to add it ourselves. Because AJAX is not a framework but just a technique to make webpages more dynamic using Javascript and DHTML, it is quite easy to use it in combination with struts.
First we make a small html form:
...
<tr>
<td><label for="first"><bean:message key="nl.company.first"/></label></td>
<td>
<!--On change the function retrieveSecondOptions() is called to populate the second box -->
<html:select property="first" onchange="retrieveSecondOptions()" styleId="firstBox" styleClass="mandatory">
<html:options collection="firstOptions" property="value" labelProperty="label"/>
</html:select>
</td>
</tr>
<tr>
<td><label for="second"><bean:message key="nl.company.second"/></label></td>
<td>
<html:select property="second" styleId="secondBox" styleClass="mandatory">
<html:option value="nothing">-First choose above-</html:option>
</html:select>
</td>
</tr>
...
Now we have to implement our javascript part:
<script lang="javascript">
var req;
/*
* Get the second options by calling a Struts action
*/
function retrieveSecondOptions(){
firstBox = document.getElementById('firstBox');
//Nothing selected
if(firstBox.selectedIndex==0){
return;
}
selectedOption = firstBox.options[firstBox.selectedIndex].value;
//get the (form based) params to push up as part of the get request
url="retrieveSecondOptionsAjaxAction.do?selectedOption="+selectedOption;
//Do the Ajax call
if (window.XMLHttpRequest){ // Non-IE browsers
req = new XMLHttpRequest();
//A call-back function is define so the browser knows which function to call after the server gives a reponse back
req.onreadystatechange = populateSecondBox;
try {
req.open("GET", url, true); //was get
} catch (e) {
alert("Cannot connect to server);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = populateSecondBox;
req.open("GET", url, true);
req.send();
}
}
}
//Callback function
function populateSecondBox(){
document.getElementById('secondBox').options.length = 0;
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
textToSplit = req.responseText
if(textToSplit == '803'){
alert("No select option available on the server")
}
//Split the document
returnElements=textToSplit.split("||")
//Process each of the elements
for ( var i=0; i<returnelements .length; i++ ){
valueLabelPair = returnElements[i].split("|")
document.getElementById('secondBox').options[i] = new Option(valueLabelPair[0], valueLabelPair[1]);
}
}
} else {
alert("Bad response by the server");
}
}
}
</script>
Finally, we have to implement the Struts Action:
package nl.company.action;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import nl.company.*
import java.io.*
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RetrieveSecondOptionsAjaxAction extends Action
{
/**
* This is the main action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws javax.servlet.ServletException
* @throws java.io.IOException
* @return
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
Logger logger = Logger.getLogger(getClass());
logger.info(
"==========================================================");
logger.info("Starting in RetrieveSecondOptionsAjaxAction");
String optionSelected = request.getParameter("optionSelected");
//Check of het soortId wel correct is
if (ValidationSupport.isEmptyString(selectedOption))
{
logger.debug("No selected option supplied");
PrintWriter out = response.getWriter();
out.print("803");
}
else
{
List options = getSecondOptions(selectedOption);
//Make a String representation where each option is seperated by '||' and a valua and a label by ';'
String outLine = makeOutputString(options);
out.print(outLine);
}
}
return null;
}
As you can see it is quite simple to use AJAX in a Struts application. The great benefit above a normal round trip to the server to dynamically update a webpage is that by using AJAX you only updated those parts of a page that have to be updated. Because AJAX performs an asynchronous call to the server the user is able to work further.

December 14th, 2005 at 23:07:16
Did you look at any of the existing AJAX frameworks like DWR? Are they any help or is it just as easy to do it yourself? There was a good session on Ajax at Javapolis yester: AJAX in Action, by Dion Almaer and Ben Galbraith. People who attended the presentation were very impressed how easy Ajax is. I believe the presenters also spent some time discussing DWR and how it helps you create AJAX applications.
December 15th, 2005 at 09:28:46
No I haven’t looked at DWR yet. But the example that I gave in my post is quite easy and fast to implement.
However, there is one problem with Ajax in Struts. When we dynamically fill the second select box and we selected a value in it, the selected valua is not selected anymore after a submit fails and the page returns with an error diplayed. This is probably due to the fact that Struts (Dyna)ActionForms can’t deal with AJAX yet and the time the ajax call is made, namely after the whole page is generated and we call
document.init to make an initial ajax call on the selected option in the first select-box. We are looking for a work-around for this problem now..
By the way, looking at your recent postings I have missed something in Antwerp
December 17th, 2005 at 04:05:11
Having some problem getting ajax to work with struts action. The url mapping in the struts-config is the same as the url that i use in request.open(“post”, url, true), but the action class is never executed.
The html:form tag looks like this: .
The config mapping for the action class is also set to /MyServlet as is the JavaScript url.
Any ideas appreciated.
December 18th, 2005 at 14:29:07
What I suggest is to try it with or without a “/” infront of the url. You have to use relative paths to stay in the application context of your webapp. I hope this will help you.
ps. I didn’t see you’re htm:form code here..
February 20th, 2006 at 22:41:34
I want to implement this solution on my project, but I can’t get what suppose to do the function call “populateRassen”. And what for and where is the element with “rassen” id in the jsp code.
Huge amount of “thank you”s.
February 21st, 2006 at 10:08:46
Hi Roberto,
populateRassen is the callback function that is called when the asynchronous call returned. You have to define your own function here. You can see in the IE-variant that this function is replaced by populateSecondBox, which is more general..I have to say that I should have been more consistent
I have changed the code
February 21st, 2006 at 21:53:18
You don’t know in what manner this come in useful to me.
I have no words to thank you.
Regards
April 4th, 2006 at 10:43:49
[...] enting dependent select boxes in JSF
Some time ago Tom Hofte wrote a post on implementing dependent select boxes using ajax in struts [...]
April 20th, 2006 at 13:16:40
When I try the above code, It is working fine when I use a jsp page as the url, but when I use an action class, Iam not getting anything in the second select box.
Can u tell me what to configure in the Struts-config.xml for the action class? As I see, the action class is returning null, I have no clue what value I should set to action-mapping forward.
April 27th, 2006 at 12:44:14
I have created following struts-ajax application
Testing struts
var req;
var which;
function retrieveURL(url)
{
if (window.XMLHttpRequest)
{
// Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try
{
req.open(“POST”, url, true);
}
catch (e)
{ alert(e); }
req.send(null);
}
else
{
if (window.ActiveXObject)
{
// IE
req = new ActiveXObject(“Microsoft.XMLHTTP”);
if (req)
{
try
{
req.onreadystatechange = processStateChange;
//var url2 = url + “?i=” + document.getElementById(‘id’).value + “&n=” + document.getElementById(‘name’).value + “&a=” + document.getElementById(‘author’).value + “&p=” + document.getElementById(‘price’).value;
req.open(“POST”, url, true);
req.send();
}
catch(e){alert(“Error=”+e);}
}
}
}
}
function processStateChange()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
document.getElementById(“theTable”).innerHTML = req.responseText;
}
else
{
alert(“Problem: ” + req.status + ” ” + req.statusText);
}
}
}
Title:
Author:
Add Book
—————————————————————————————————————————
This one is the BookForm
package pack;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class BookForm extends ActionForm
{
private String mTitle= null;
private String mAuthor= null;
public String getTitle() { System.out.println(“in getTitle”);return mTitle; }
public void setTitle(String aTitle) { mTitle= aTitle; }
public String getAuthor() { return mAuthor; }
public void setAuthor(String aAuthor) { mAuthor= aAuthor; }
public void reset(ActionMapping aMapping, HttpServletRequest aRequest)
{
mTitle= null;
mAuthor= null;
} // reset()
} // BookForm class
—————————————————————————————————————————-This is BookAction Class
package pack;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import java.sql.*;
import java.io.*;
public class BookAction extends Action
{
public ActionForward execute(ActionMapping aMapping, ActionForm aForm, HttpServletRequest request, HttpServletResponse response) throws ServletException
{
BookForm f = (BookForm) aForm;
String title = f.getTitle();
String author = f.getAuthor();
System.out.println(“>>> Saved: ” + title + ” by ” + author);
try
{
String html=”";
Class.forName(“org.gjt.mm.mysql.Driver”);
Connection con=DriverManager.getConnection(“jdbc:mysql://Mac5:3306/person”,”root”,”admin”);
Statement st=con.createStatement();
st.executeUpdate(“insert into newtable values (‘”+title+”‘, ‘”+author+”‘);”);
//st.executeUpdate(“delete from newtable”);
ResultSet rs=st.executeQuery(“select * from newtable;”);
html = “”;
while(rs.next())
{
title=rs.getString(1);
author=rs.getString(2);
html+=”"+title+”"+author+”";
}
html += “”;
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(html);
request.setAttribute(“myhtml”, html);
return null;
}
catch(Exception e)
{System.out.println(e);}
return aMapping.findForward(“saved”);
} // perform()
} // BookAction class
—————————————————————————————————————————-
This is savedOk.jsp
—————————————————————————————————————————-
This is struts-config.xml
————————————————————————————————————————–
Problem is that when i click on Add..(ajax call through open()) Button i am getting null values from BookForm where as if i clicks on submit(normal call to action) it works perfectly.
plz anybody master help me out of this……..
thanks
Manoj(manoj.amrutkar@yahoo.com)
May 29th, 2006 at 14:07:36
I tried Google first before implementing my own dependent dropdowns with Java-Script(Ajax):
http://66.93.253.166:8080/ajaxtags/dropdown.jsp
This Tag-Library works fine.
July 21st, 2006 at 17:00:16
Hi,
please forward the above code, to have a clear picture on usage of ajax tags.
Thanks,
Mahesh Dasari
maheshbabu.d@gmail.com
July 27th, 2006 at 14:35:28
Hi,
Struts and ajax is working fine together, but do any of you have any experience in mixing Struts, Portlets and ajax together?
July 28th, 2006 at 08:31:57
Hello,
I have tried your example and it is one good, even your posted code has some errors, but at the end it is an educative example … and thank you for your work.
I have just one question. When I run my website (which is under construction) those two dropdownlists work very well – I mean than the second dropdownlist show the real values. But, when I make some modification on that values (I modify the values in database), that second dropdownlist does not show the updated values. (I mean that for a specific selection of the first dropdownlist, the second will show just old values and not the updated values). Do you have any ideea, why?
Nick
July 28th, 2006 at 09:14:23
Hello Jorid,
To integratie it with portal you have to use absolute url’s. What you could do is to store the server-path and context-path in a session variabele in you index action and then use these variables to build the AJAX url.
This should work!
July 28th, 2006 at 09:15:32
Hi Nick,
You problem has probbly to do with caching. Add this statement to your action class:
//Set no-cache
response.setHeader(“Pragma”, “no-cache”);
July 28th, 2006 at 10:28:07
Hi Tom,
thank you for your prompt response. You had right, that issue was from cashing.
I have tried with : response.setHeader(“Pragma”, “no-cache”); and it didn’t work first.
I have tried it together with : response.setHeader(“Cache-Control”,”no-cache”); and it works very well.
Thank you Tom
July 28th, 2006 at 14:55:08
Hi Tom,
thanks for your reply, but i can’t get it to work yet. I can communicate with other servlets, so i do communicate with the web.xml, but i can’t get it to communicate with the Struts servlet and the struts-config.xml. When i use the struts-tags my path looks like this:
I think i have to produce something equal, but i don’t know how.
any suggestion?
July 28th, 2006 at 14:57:17
Here comes the path:
July 28th, 2006 at 14:58:27
sorry…
“/wps/myportal/.cmd/ad/.ar/sa.spf_ActionListener/.c/58502/.ce/58511/.p/58507?PC_58507_spf_strutsAction=!2fselectRefundApplication.do!3ftype=S!26index=0#58511″
July 28th, 2006 at 15:04:17
May be this wil work. But I use my application url e.g. http:////youraction.do
if you secure your application well this should be no problem…
However, you also could not use Portal
July 28th, 2006 at 15:40:41
Hi Tom,
do you have any resonable ideea how to solve the issue you posted :
“However, there is one problem with Ajax in Struts. When we dynamically fill the second select box and we selected a value in it, the selected valua is not selected anymore after a submit fails and the page returns with an error diplayed. This is probably due to the fact that Struts (Dyna)ActionForms can’t deal with AJAX yet and the time the ajax call is made, namely after the whole page is generated and we call
document.init to make an initial ajax call on the selected option in the first select-box. We are looking for a work-around for this problem now..” ??
Because I try to find a solution for those dropdownlists.
Best Regards, Nick
July 30th, 2006 at 13:39:21
Hi Nick,
I have solved this problem by storing the selected values in the request object. After we made the intial ajax call on the selected object in the first select-box to fill the second box, we use the value in the request object to the select the right value in the second box.
Hope this will help you!
July 31st, 2006 at 23:16:15
Hi Tom,
This was very helpful but can you also please explain how to dynamically load checkboxes. I have the String from server side but unable to display it. For you secondBox was a html:select but for me it is a html:multibox.
” />
…..
August 1st, 2006 at 09:05:26
Hmmm, I do not have experience with your issue. But I think you will have to build the multibox dynamicaly and add it to your site. Maybe you construct the html on the server and send it back to the browser, where your callback function will display it in the right place on the screen
August 1st, 2006 at 13:58:45
hi,
I have read this article. Its simply grt.
One thing i want to ask here regarding the url creation.
the action which is in the url should be defined in the struts-config, like other actions RIGHT??
I have done that.
Now the problem is currently if i am in some directory one or two levels down to my context,
for ex. if my context is till (http://localhost:8040/struts-ajax/) and i m in (http://localhost:8040/struts-ajax/templates/) directory.
and from there if i use this approch then error gets generated, it says “Invalid path was requested /templates/findStates”. Here findStates is my action name.
It should not use “templates” while sending request..
Now what should i do..??
Thanks in advance.
August 1st, 2006 at 17:08:45
Thank you Tom for your advice,
It helped me and everything is working well, even I found it not very elegant because to upload the first dropdownlist I need to go on the server to get values, and for submit I have to get the list with the possible values for the second dropdownlist – to populate it. The Ajax technic is working well anyway and thank you for your help.
Anyway, it was my first attempt in Ajax, and with your help I solved it. Thank you again.
I have just one more question, maybe one stupid, but I don’t have so much experience and I don’t know what is the cause. It’s good any idea.
Right now, I observe that the status bar of my explorer have a message like this “Error on page” and it appear when I make a new selection in the first dropdownlist. This message is temporar, and then it became “Done”, but with this sign : “!”.
I know that you laugh, but sincerlly I don’t know how to solve it.
Nick
August 1st, 2006 at 20:02:41
The error message in the IE status bar is due to an javascript error. you can clivk on the error to see what is going wrong. I have to admit that the error messages of IE are a bit poor (Firefox has better so try it in there). You have to debug your javascript code by using alert(“My code had reached here”); statements in it. Be very systematic in debugging javascript!
succes
August 8th, 2006 at 22:42:30
why is null returned from the action class.
where are you setting the options string constructed in the action class in request.
I dont see how did you access it in jsp.
Thanks
August 9th, 2006 at 09:07:41
Hi Deep,
Tom’s example is just to present you a modality to use Ajax with Struts. You don’t have to follow step by step this example. Try to understand it. It’s very simple and educative. In RetrieveSecondOptionsAjaxAction class (which is an Action type) he take the values of the second box, using a string which is returned to the client. The response is received in an asynchronous way, and he will parse it to update the second box. In action class you have to return an ActionForward object used for the next step in your application. So, the response is not accessed in the jsp. It is accessed in js code, and then the jsp will be updated.
August 9th, 2006 at 09:24:04
Thank you Nick for your explanation
Deep,
You can use my code examples as a starting point and you can just add your specific things to it. The main clue in my example is that I return null in the Action class, because I only want to response outside the Struts controller with an encoded String back to the same page to update it. In my example the getSecondOption method is just the template method you have fill in by yourself for your own specific needs.
Succes!
August 11th, 2006 at 09:42:00
Hi,
I have wrote common functions like retrieveText(url, textElementId) and populateText(textElementId).
I have changed javascript:
req.onreadystatechange = populateText(textElementId);
(and another not so important changes)
populateText(textElementId) is called properly, but it doesn’t print any text. (sorry for my English
)
August 11th, 2006 at 19:00:34
Can you make sure by debugging that the call-back function is really invoked?
You can use alert() statements to debug you javascript code…
August 11th, 2006 at 21:10:21
The firefix firebug plugin is very usefull for debugging javascript, it will display log messages which you create using console.log() in javascript.
August 16th, 2006 at 14:39:01
hi,
i am new to struts and Ajax,
I have read this article. Its simply grt.
it working for me but i got one problem that when i select one item from select box at
first time it gives Bad response by the server
after next selection of that item it will work properly
but every first time i got Bad response by the server
is there any solution for that plz tell me
thanks
August 18th, 2006 at 23:48:04
Hi Rahul,
. Anyway maybe I am not the right person to advice you, but please believe what Tom said :
I am also new to struts and Ajax, but I try to grow up
“Can you make sure by debugging that the call-back function is really invoked?
You can use alert() statements to debug you javascript code… ”
this can be very useful to you. If you debug your javascript code and your java code (from struts) you’ll find the issue. The explanation of your problem is not detailed, so …
Try to debug your code, step by step, even with alert messages as Tom’s advice or follow Andrej’s advice. If you know the communication process you’ll quickly find the solution.
August 26th, 2006 at 09:41:02
I do have the same problem what mano has stated above.
when I insert into my html page,
A null pointer is thrown where as if I remove this line every thing is working fine.
I have placed my Ajax.js in the same folder where I have my html page.
Why is it giving exception Please help.
Regards:
Yash
August 28th, 2006 at 09:17:50
thankx a lot
August 31st, 2006 at 12:53:38
Hi
I am new to Ajax
I am trying one exmple (ajax-struts) but the action class is returning null i am not getting why is it so
can u give me sum hints to solve this problem
August 31st, 2006 at 12:54:16
Hi
I am new to Ajax
I am trying one exmple (ajax-struts) but the action class is returning null i am not getting why is it so
can u give me some hints to solve this problem
September 4th, 2006 at 11:42:14
Hi all,
Ajax works great, but I’ve encountred another problem – please help me with a solution:
After the user made his selection using the select boxes he clicks submit, but then he might want to go back to the previous page. The page then displays the original page’s selection options, an not the ajax generated selection options for the select boxes. How do I get the page to keep the selection and options of the user after submission and going back?
Hope my question is clear enough!
Thanks
Mieder
September 4th, 2006 at 11:47:21
Hi Mieder,
You have to store the selected value of the second select box in request variabele and when the process Action fails and returns to the page the request variabel is used to select the appropriate value in the second box.
Make sure you use documment.init = retrieveSecondOptions(); to initialize the second box. You will have to adapt thsi function to select the right value.
Success!
September 14th, 2006 at 09:02:03
Hi Tom,
thank you again for your example. I have developed a web application using Struts, and some elements in the user interface are done with ajax [some dropdownlists]. Everything is working fine, BUT JUST IN IE. I have tried running it with Firefox or Opera, and nothing is going well. I have started to debug step by step to see what’s going on, because that’s not good…
If you have any sugestions, let me know.
Nick
September 14th, 2006 at 09:37:58
Hi Nick,
Please make sure that you are privileged to use Javascript in Gecko-based browsers like Firefox and Opera. Also check if you have an XmlHttpRequest object..
Succes!
-Tom
September 16th, 2006 at 09:14:12
Hi
October 15th, 2006 at 10:23:35
Hi,
Can you please explain me how to pass the xml output fron Action class to AJAX callback function?
Also can you mail me the full code for autocomplete which you showed above?
Thanks.
October 15th, 2006 at 10:26:51
Hi,
Can you please explain me how to pass the xml output fron Action class to AJAX callback function?
Also can you mail me the full code for autocomplete which you showed above?
My mail is: mail_me@muchomail.com
Thanks.
October 15th, 2006 at 14:15:36
Hi,
you can use:
PrintWriter out = response.getWriter();
out.print(“803″);
to write the response text:
and you use:
output = req.responseText;
in the javascript callback function.
Hope this will help you out.
October 30th, 2006 at 23:29:19
invoProblem:
AJAX Struts action is blocked while another Struts action is active from the same web client:
Case desciprtion:
action a1 is long running — takes up to 30 minutes or longer
action a2 is hit/and/run to get some string data from the server. is invoked via AJAX call every seconds while a1 is executing.
STRUTS: 1.1
Browser: IE 6
Container: Tomcat 5.5.17
AJAX: javascript using XmlHttpRequest object
Run scenario:
1) http://…/foo/Foo.do?action=a1
2) Foo.jsp contains the AJAX call, invoking url: /Foo.do?action=a2 every second
Symptom:
1) Whence a1 is under way (before return), a2 action is ‘blocked’ — never gets to be processed!
2) a2 gets executed BEFORE and/or AFTER active a1 action!
3) a2 gets executed every time if from another web client regardless a1 is active.
Is AJAX call an independdent client request? or behaves like one?
Thanks
October 31st, 2006 at 10:53:30
Maybe the symptom is due to the fact that you are working with the same XmlHttpRequest instance. That’s what I can identify as the possible cause of the symptom..
November 3rd, 2006 at 15:46:55
Hi,
I’m using Ajax with Struts. I have an example using the same ideas as those in your example. Everything goes well if I’m using the GET method to invoke the url of my action. But if I’m using the POST method, inside my action, I can’t obtain the values set with the send() function; only null values instead. Is there something special to do to send the data in a POST?
I found that I should use
req.setRequestHeader( “Content-Type”, “application/x-www-form-urlencoded”);
in order to have my POST working, but when I put this code line I get an exception with the description: “undefined”
This is the code used:
function ajax_Query( url, parameters, callbackFunction)
{
if( url != “”) {
if( window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
}
else if( window.ActiveXObject) { // IE
try {
req = new ActiveXObject( “Msxml2.XMLHTTP”);
}
catch( e) {
try {
req = new ActiveXObject( “Microsoft.XMLHTTP”);
}
catch( e) {}
}
}
if( !req) {
alert( ‘Impossible de creer une instance XMLHTTP !’);
return;
}
try {
//req.setRequestHeader( “Content-Type”, “application/x-www-form-urlencoded”);
// Set the callback function.
req.onreadystatechange = callbackFunction;
// Open a connection.
req.open( ‘POST’, url, true);
// Send data to the server in ‘POST’ method.
// Ex: “name=value&othername=othervalue&andso=on”
// Note: null parameter if the ‘GET’ method is used.
req.send( parameters);
}
catch( e) {
alert( ‘Description erreur : ‘ + e.description);
}
}
else
{
alert( ‘Le lien d\’invocation d\’une action n\’a pas ete specifie !’);
}
}
Any other idea?
Thank you
November 3rd, 2006 at 18:42:57
Hi again,
well, the setRequestHeader() is really needed, but looking to the specifications:
http://www.w3.org/TR/XMLHttpRequest/
it must be called only between open() and send() functions.
But that’s not enough to solve the problem of my null parameters inside my action. The charset was also needed. So the code line needed was:
req.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded;charset=UTF-8;’);
Hope you’ll find that usefull.
November 11th, 2006 at 17:02:37
Tom:
Thanks for your analysis of my case.
No. They are NOT the same XmlHttprequest instances. Each invocation uses a new instance.
More over, action ‘a1′ is a regular web/struts, not a AJAX call at all, the ‘a2’s are AJAX calls.
Could AJAX be mixed with none-AJAX calls” as:
FooForm/FooAction (executes ‘a1′ and ‘a2′ actions, ‘a1′ being long running)
From the SAME WEB CLIENT(the same session):
1) a none-AJAX invokes ‘a1′, keep running without return
2) Multiple hit/and/run AJAX calls in while ‘a1′ is still executing
3) Action codes for ‘a1′ and ‘a2′ are separated two methods, not under and inside single ‘execute’ method.
What the threading model does STRUTS use?(when the form/action, is session scoped)
Is STRUTS action servlet ’synchronized’?
Thanks
November 20th, 2006 at 21:58:18
Thanks Tom, this was very helpful
November 21st, 2006 at 12:17:30
Tom,
In my application on the same lines,I’m receiving the response on the same jsp but as soon as the response comes ,the application automatically navigates to some diif(blank) page. I don’t understand whether it is due to struts-config or something else.I’m returning actionforward as null from my action.
Thanks
December 12th, 2006 at 17:43:50
Hi
I’m trying to do a multi-select form with AJAX. The form contains three “select fields” and the second depends fron the one and the third from the second (AJAX). I’ve done the first and the second one but I don’t know how can I do the third one because I have in separated files the code where I do the search to fill the second select and I only call it by Ajax, but I don’t know how to do that for three.
Someone could help me?
Thanks.
December 14th, 2006 at 02:37:42
Your script works fine except, that it is adding a line break in the value of a select parameter when the form is submited. The value of the select option
can there for not be properly retrieved. Any ideas???
December 31st, 2006 at 07:11:33
[...] Ajax in Struts: implementing dependent select boxes. [...]
February 1st, 2007 at 06:33:42
Hi,
I implemented the above mentioned logic in my project. I am getting the second box being populated by some html tags from the header.jsp.
In the action class, i didn’t set anything in the response. Though, i am getting those craps in the select box.
Kindly help me to fix this bug.
Rgds,
M.
February 20th, 2007 at 11:13:25
please send me a clear cut example of how to use struts in ajax,as im new to this concept
March 23rd, 2007 at 15:13:04
please send me a clear cut example of how to use struts in eclipse (SDE3.0)
March 27th, 2007 at 15:11:04
Hi,
I am working with Ajax. I am facing one problem.I am passing the values to js and to server.After that I am getting “req.status” as 500.What could be the problem.
March 27th, 2007 at 15:17:00
Hi,
HTTP code 500 indicates that an internal server error occured. Probably, something went wrong on the server. So I advise, you to debug your server code to check if something is going wrong
Kind regards,
-Tom
April 27th, 2007 at 16:53:37
Hi Tom,
I am working with Struts and Ajax. I have requirement in UI where in thre are two multi-select list boxes…and I need to populate and dynamically change the second one based on the selections in the first one. Can u help me with a example of that.
Thanks,
Rachit
April 30th, 2007 at 11:19:23
I think you can use the example above, but need to send a string of all the selected options in the XMLHttpRequest.
May 10th, 2007 at 21:30:05
Hi am trying to post querystring data via AJAX. I keep getting an “There was a problem with the request status = 500″ error. Can anyone assist me…thank you so much.
Reg
May 11th, 2007 at 09:47:19
Hi Reggie,
A 500 code indicates an internal server error. I advise you to debug your server code.
Regards,
Tom
July 16th, 2007 at 16:06:16
I am fresh at using Ajax with Struts.
I have a page where depending on the users click action, call is made to the struts action class using Ajax.The Ajax retrieves some values from database and puts it into a different jsp page.I want to append this jsp page to the original page.But the problem is since I’m using the struts tag library tags the jsp page is not getting loaded.Normal html pages load but jsp pages which contain struts tags are not getting loaded.
Thanx in advance.
July 18th, 2007 at 09:29:06
Hi,
The reason that you’re appended jsp page is not showed is that the struts tags are evaluated on the server. Because you’re are doing a partial page update this is not happening.
What you can do is setting a boolean value in the request (or session) that indicated whether a part the JSP page needs to be showed or not. I think you should forget the idea of a separate JSP page.
Success!
Tom
July 23rd, 2007 at 15:20:45
Hi Tom
i am trying to access form bean which is in session scope through DWR, when ever i call the methods in javascript the returned values are empty.
how to get the values in jsp page ?
August 6th, 2007 at 14:47:54
i am new to ajax. i am trying one example ajax in struts.
in action class i am getting null values. but normal struts (frmname.submit) it works fine.
can anybody help me..
August 31st, 2007 at 08:36:04
can any body help me in getting code for three drop down boxes in ajax using servlet on server side
September 18th, 2007 at 09:14:12
hi all,
i Used this code with the dispatch action but
it does not call my DispatchAction class what should i do
December 17th, 2007 at 16:13:15
Hi,
Very simple and good example. I am looking for seemless integration of AJAX and struts. My hunt ends here. Thanks.
Ankur Shah
December 24th, 2007 at 12:25:40
Hi,
Can you publish the entries required in struts-config.xml to get this example working. I have coded my application as you have suggested but every time my action is invoked it just prints the text on the browser and that too on a new page.
Rahul
January 17th, 2008 at 12:25:33
Hi
can u publish the detailed code of the dependent select box.Can u tell me whats the need of splitting data .Please give the code for makeString function also.
Suresh
February 6th, 2008 at 00:33:45
Hi I am getting “Bad response by the server” as I select each item, callback function gets called with the alert request.readyState – 1,2,3 and debugging the flow does not enter the RetrieveSecondOptionsAjaxAction.execute method, any suggestions?
February 7th, 2008 at 23:23:53
I got my solution, I added request.getContextPath() before the url and it worked like a charm.
February 11th, 2008 at 22:27:47
Hi Tom,
Thank for this useful example. My case is a little bit different, but not too much. The content for the second box is retrieved from database based on the selection of the first box.
So my first question is that how to pass that value to the Action class after clicking the first box? I tried to use form. getSourceSystem() method (sourceSystem is a property of the Form class). It had nullpoint error.
The second question is that how to pass the values for the second box to JSP to display?
These might be the naïve questions, but please help me out. Thank you very much in advance.
Everett
April 29th, 2008 at 18:19:55
will the method ‘retrieveSecondOptions’ will have to be called explicitly for first time page load if we are generating html and doing response.write and having such code
..i dont know much about struts but same type of pattern i have to use..
April 29th, 2008 at 18:22:26
heres the code section that merged into page html..
April 29th, 2008 at 18:23:48
will the method ‘retrieveSecondOptions’ will have to be called explicitly for first time page load if we are generating html and doing response.write and having such code
html:options collection=”firstOptions” property=”value” labelProperty=”label” selected
..i dont know much about struts but same type of pattern i have to use..
May 24th, 2008 at 16:48:29
Nice topic
Thanks
I have found two interesting sources ( Fileshunt.com and Filesfinds.com ) and would like to give the benefit of my experience to you.
August 6th, 2008 at 09:00:50
It is superb. Thank you so much. I have implemented Ajax in my project now refering to this example.
August 9th, 2008 at 01:14:09
Very tnx to Tom Hofte July 28th, 2006 at 09:15:32 this post was very helpful, i haved a problem with a select on an iterator with struts, i was updating status and sometimes works and sometimes not i´ve tried setting pragma and Cache-Control before on script and jsp, and assumed that there was a problem with the struts version beacuse same code with a prior release works fine, after change the same header params on action it works for this relase too, THANKS So much.
November 3rd, 2008 at 15:41:07
hi
i had html dom object for select box. on loading the my jsp. i am populateing items in to that select box by ajax call to action class.
for the first time on loading the jsp , i am unable to see the items in the selectbox(not getting response from server). when i refresh the same page , am getting the items in select box.
could u please let me know what might be the fix or work around to to get the items first time on loading the page.
thanks in advance.
November 18th, 2008 at 16:51:38
Hi I am not getting the ready state == 4
Dont know the reason.
I implemented the code according to you.
Please help me out
November 25th, 2008 at 00:57:04
Hi Tom,
PrintWriter out = response.getWriter();
out.println(html);
By using writer object are we not going back to the age of Servlets…Any other best way to replace it.
December 30th, 2008 at 15:23:38
Hi
I am getting “Bad response by the server”. But my action is being called and it generates the output String and PrintWriter writes it also.
But atlast i get “Bad response by the server”. Can anyone please help me.
Thanks.
Selvam
February 10th, 2009 at 16:46:22
hi i’m new to struts.i have to implement two dependent select boxes in struts.To retrive the value of first select box i have used a header link.To display the value in the second select box first box get submitted to the server and an action is called but the problem is when the action for selecting second select box is called the first select box value bean goes out of scope so it gives the error.both select boxes r in the same form.
i got frustated with this problem please if some one guide me …???thanks in advance
February 19th, 2009 at 20:53:20
Ñïàñèáî Âàì çà Âàøó ðàáîòó.
February 22nd, 2009 at 16:15:23
Ñïàñèáî çà Âàøó ðàáîòó.
February 23rd, 2009 at 20:11:49
Çàìå÷àòåëüíûé ñàéò, ñïàñèáî.
February 24th, 2009 at 13:09:57
Õîðîøèé ñàéò, ñïàñèáî.
March 5th, 2009 at 11:33:44
This does’t solve my problem, why do I always need to steal Information.
java.lang.SecurityException: PWC1404: Servlet of class {} is privileged and cannot be loaded by this web application
March 26th, 2009 at 22:52:21
Ñóïåð
July 14th, 2009 at 08:47:10
Hello,
i m new for strut with ajax. when i was trying to use this code then it was not working. probably due to struts-config.xml file. So please give details about that config file.
Regards,
Brij
July 15th, 2009 at 23:37:49
Just want you to know this person hijacked your post and published it as if he wrote it. http://java2flex4u.blogspot.com/2009/06/ajax-in-struts-implementing-dependent.html
November 25th, 2009 at 17:44:44
just a small correction who is stucked with BAd request alert like me. Check returnElements arrays in the code. some of them written as returnElements and some of them returnelements like in for loop. After copy paste this can happen
Thanks for post BTW. It is really useful example…
December 2nd, 2009 at 13:46:11
Hi,
Using above logic my struts-ajax application working fine,but now i am facing problem that while getting value of my action form it show null e.g.when in actionclass i am calling WelcomeActionForm welForm=(WelcomeActionForm)frm;
welForm.getT2();
i am getting null value.why?Plz reply
March 19th, 2010 at 19:24:31
Good post. I don’t suppose you’d be against it if I added your blog to my linkexchange directory?
May 28th, 2010 at 21:38:46
I am trying to test this solution with strus 1.3, IE8 and firefox 3.5
I am not able to send the request to server get the response but the function populateSecondBox() is not doing the job of populating the second dropdown.
Any suggestions/guess why it may be failing would be appreciated.
Thanks
jd
May 28th, 2010 at 21:39:39
small correction … I mean I am able to send the request
June 7th, 2010 at 05:31:03
Need to create a sth like this into a php file for a online registration step to select country and organization from the database of country and organizations and inserting into the application table.
All is done the only need is to create the form with this characteristic into the the existent file.
August 25th, 2010 at 20:07:06
Read about jQuery $.ajax, $.get, $.post is more easy!!!!. I use that with struts .
saludos.