Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Tuesday, June 17, 2008

JSON with AJAX

Example shown to use AJAX and JSON to dynamically populate a dropist.
When droplist 1 is changed, droplist 2 get refreshed with data sent from the server through an AJAX call in a JSON format.

Droplist 1
<html:select property="personCode" onchange="getPersonType();">
<html:option value="" > </html:option>
<html:options property="personCodeList"/>
</html:select>

Droplist 2
<html:select property="personType">
</html:select>


<script>

function getPersonType()
{
var selBox = document.personViewForm.personCode;
var personCode = selBox.options[selBox.selectedIndex].value;
var url = "/Orion/ajax.do?method=getPersonType&personCode="personCode;

var jsonReq = new Json.Remote(url, {
async: false,
autoCancel:true,
onComplete : function(personTypeList){ populatePersonType(personTypeList);
}}).send();
}


function populatePersonType(personTypeList)
{

var selBox = document.personViewForm.personType;
selBox.options.length = 0 ;
selBox.options[0] = new Option("", "");

for(i=0, len=personTypeList.length ; i<len ; i++)
{
selBox.options[i+1] = new Option(personTypeList[i], personTypeList[i]);
}
}

</script>

import net.sf.json.JSONArray;
import org.apache.struts.action.Action;

public class AjaxAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {

// this Action is not mapped to a form and does not use a JSP for view,
// thus form and mapping and not neccessary

try {
String method = request.getParameter("method");

if("getPersonType".equals(method))
{
doGetPersonType(request, response);
}
else{
// send an error if "no such method"
doTheExceptionThing(request, response);
}

} catch (Exception ex) {
doTheExceptionThing(request, response);
}
return null;
}

private void doGetPersonType(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String personCode = request.getParameter("personCode");

List<String> list = DatabaseHelper.getPersonTypeList(personCode);

JSONArray array = JSONArray.fromObject(list);
String s = array.toString();

response.setContentLength(s.length());

PrintWriter output = response.getWriter();
output.print(s);

output.close();
}

private void doTheExceptionThing(HttpServletRequest request, HttpServletResponse response) throws Exception {

// since this action is used by a background Javascript invocation, there's not much error to be sent
// or seen by the client. We'll just send a generic error message.

response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("error");

}

}

Required libraries - json-lib-2.1-jdk15.jar, mootools.js