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...

[516 byte] By [Greeshma12a] at [2007-11-27 10:16:00]
# 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 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Thanks for your reply...

It helped me a lot, but I have a question, I'm not using struts but follow the MVC design pattern, I have a method in dopost which does the functionality and then the dispatch() is called to go the next jsp, my Question is by doing this I'm I loading the page again ...I'm I misusing or misunderstanding AJAX...

Thanks,

Greeshma...

Message was edited by:

Greeshma12

Greeshma12a at 2007-7-28 15:42:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

I have only worked using struts and MVC model. When you want to use AJAX (dynamically interacting), why should the page reload?

skp71a at 2007-7-28 15:42:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

I'm confused ..Can anyone answer my question ...

My question is at the end of the dopost() I forward request from Servlet to JSP using requestDispatcher.forward(request,response); ..then is it not loading the jsp again ...how come only the dropdown data is repopulated ...

And I'm not able to pass the queryString using AJAX...

Help is greatly appreciated...

Thanks,

Greeeshma...

Greeshma12a at 2007-7-28 15:42:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

The whole point of using Ajax is that you DON'T refresh the entire JSP page.

You only load some extra info, and then use javascript to modify the page in place - in your case change the options which appear on your list.

If you want to reload the entire page, then you don't use Ajax.

evnafetsa at 2007-7-28 15:42:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

Thanks for your reply ..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 or when we use MVC in the dopost() method we use RequestDispatcher.forward.So, when we do something like this to display the jsp are we still following AJAX without reloading the page...

Thanks,

Greeshma...

Greeshma12a at 2007-7-28 15:42:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 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

evnafetsa at 2007-7-28 15:42:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 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

RahulSharnaa at 2007-7-28 15:42:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 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...

Greeshma12a at 2007-7-28 15:42:52 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...