dropdown-ajax
Hello All,
I have a requirement such that based on a selection within the first drop down field, a second select field should be populated.I'm thinking of using AJAX for this. I'm clear about how to send the request to the server, I have a Database call from my action class that returns a list, I'm not sure how to display the list as a drop down in my jsp,i.e., not clear how to display the response. I'm using MVC design pattern.
Help is greatly appreciated.
Thanks,
Greeshma...
# 1
Here you go, this is I wrote for my jsp:
//create XMLHttpRequest object
function getHTTPObject() {
var xmlhttp;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject){ // if IE
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch ( e ){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch ( e ){}
}
}
return xmlhttp;
}
var httpObject = getHTTPObject(); //global variable
function getSecondListValues() {
var URL = "getValues.do"; //have action mappings in struts-config.xml
var selectedVal = '';
var selObj = document.getElementById('<fisrt combo box name here>');
var selIndex = document.getElementById('<fisrt combo box name here>').selectedIndex;
selectedVal = selObj.options[selIndex].text;
var queryString = "selectedVal="+escape(selectedVal);
httpObject.open( "Post", URL, true );
httpObject.onreadystatechange = attrResponse;
httpObject.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
httpObject.send(queryString);
}
function attrResponse() {
if (httpObject.readyState == 4)
{
if (httpObject.status == 200)
{
var getVal = httpObject.responseText; //gets all the output values from the action class
var valarray=getVal.split(",");
for (var i=0; i < valarray.length;++i){
addOption(document.getElementById("<second combo box name here>"), valarray[i], valarray[i]);
}
}
}
}
}
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function addOption(selectbox,text,value)
{
var optn = document.createElement("OPTION");
optn.text = trim(text);
optn.value = trim(value);
selectbox.options.add(optn);
}
//use this fn to clear values in the second select, when first select values changes
function removeAllOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
selectbox.remove(i);
}
}
//your action class should be something like below:
public class GetAttributeValuesAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String forward = "success";
String selectedVal = request.getParameter("selectedVal"); //get the first select value
HttpSession session = request.getSession( true );
ActionErrors errors = new ActionErrors();
String value = null;
try {
if(selectedval != null )
{
ArrayList val = new ArrayList();
//use your logic and get the second select values
//comma seperated
for( int i = 0; i < val.size(); i++)
{
if( i == 0)
{
value = val.get(i);
}
else
{
value = value + "," + val.get(i);
}
}
}
} catch (Exception e) {
}
PrintWriter out = response.getWriter();
out.println(value);
// Finish with
return null;
}
skp71a at 2007-7-28 15:42:52 >

# 7
>but in the source code above when we use struts we should return >ActionForward which leads to the destination to which the controller, might be
>directed to perform a RequestDispatcher.forward
That is the normal pattern in struts. Most cases you send a request (click a button/link) and you want an HTML page in response to replace the one currently in the browser window.
But AJAX is different. You still want to send a request and get a response, but you want to leave the current page as is. For that you use the javascript HTTPRequest component. In this case the response wanted is not an HTML page, but just a comma separated list of values to put in the select box.
This struts action is different. It doesn't return an actionForward. Instead the action returns null, which informs struts that "I have taken care of the response thank you very much, you don't need to do anything".
This action has taken care of the response itself (sending a comma separated list of values) and doesn't need or want Struts to do anything else.
In this case, the response is a comma separated list of values.
The response gets sent back to the javascript HTTPRequest component.
That then calls the javascript function attrResponse which gets the comma separated value list, and uses it to populate the select box using javascript.
You have send a request, got a response, but the page didn't have to reload - it just used javascript to modify the existing page.
Hope this helps,
evnafets
# 8
well i completely accept with wat my fellow poster have said...
Ideally...If you are not intrested in disturbing MVC pattern which a targeted framework follows or to any customized approach of urs....
here is how you can do it.....ideally...
Targeted Page(XmlHttpRequest)->
Controller-(Call model and then frame XML/JSON/CSV response & save it in the Form Bean & fwd it to a jsp)-->
JSP (JSP reads the content of the form bean and outputs text/xml response) -->
Targeted Page receives the response outputed by the JSP
(Parses the response got and updates the view accordingly).
Hope that might cleared it out...
REGARDS,
RaHuL
# 9
Hello All,
Thank you for your replies.I'm following a framework that follows MVC
I have my dopost() as:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
boolean istrue = false;
//I'll put the response in session
istrue = doAction(request);
if(istrue) {
RequestDispatcher requestDispatcher = request.getRequestDispatcher(nextPage);
requestDispatcher.forward(request,response);
}
else
//error page
}
}
And in my doAction() that I have to implement at the end of the method I have something like this:
HttpServletResponse response = (HttpServletResponse) mySession.getAttribute("response");
PrintWriter out = response.getWriter();
out.println(value);
istrue = true;
So, my Question is after the doAction() return true the dopost() forwards the request to the next URL so are we really reloading the whole jsp again...I'm I doing it correctly ?
Help is greatly appreciated.
Thanks...