Thursday, June 12, 2008

Populate droplist dynamically through AJAX

Mechanism to make an ajax call from one drop list and populate another droplist


In JSP

Add a html select element as below

html:select name=somethingOne id=dropListOne onchange="retrieveDropTwoOptions()

html:select name=somethingTwo id=dropListTwo


function retrieveDropTwoOptions(){

dropListOne = document.getElementById('dropListOne');
if(dropListOne.selectedIndex==0){
document.getElementById('dropListTwo').options.length = 0;
document.getElementById('dropListTwo').options[i] = new Option("---", "", true);
return;
}
dropListOneCode = dropListOne.options[dropListOne.selectedIndex].value;
url='/MyServer/ajax.do?method=populateDropList' +
'&dropListOneCode=' + dropListOneCode ;


//Do the Ajax call
req = ajaxRequestSend(url, "GET", populateDropListTwoBox);

}

//Callback function
function populateDropListTwoBox(){

if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
textToSplit = req.responseText;

myCode = document.getElementById('dropListTwo').value; // obtained from form
//Split the document
returnElements=textToSplit.split("\n")

//Process each of the elements
document.getElementById('dropListTwo').options.length = 0;
for ( var i=0; i valueLabelPair = returnElements[i].split(":")
if (myCode == valueLabelPair[0]) {
document.getElementById('dropListTwo').options[i] = new Option(valueLabelPair[1], valueLabelPair[0], true);
}
else {
document.getElementById('dropListTwo').options[i] = new Option(valueLabelPair[1], valueLabelPair[0]);
}
}
}
}


function ajaxRequestSend(url, method, callBackFunciton){
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open(method, url, true);
req.onreadystatechange = callBackFunciton;
req.send(null);
return req;
}


In AjaxAction.java, we add a simple method to return a value

public class AjaxAction extends Action
{
//...

public void populateDropList()
{
StringBuffer body = new StringBuffer(":---\n");

//... get data from database

while (resultSet.next()) {
code = resultSet.getString("code") ;
desc = resultSet.getString("name") ;
body.append("\n").append(code).append(":").append(desc);

}

response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(body.toString());
response.getWriter().flush();

}

}

No comments: