Monday, February 12, 2007

Java + AJAX in 18 lines

I have been investing a fair amount of time learning the Dojo Javascript library but I had an application where I only needed AJAX to handle HTML form input - I wanted a server side function to return HTML to be inserted below the form. Dojo is a huge library so I pulled the prototype.js library out of one of my old Ruby Rails projects (prototype.js is only about 70KB). I put the following in my form JSP page:
<form id="myForm2">
 <input type="text" id="input_test_form_text" />
 <input type="button" value="Search" onclick="getS()" />
</form>
<div id="searchresults"></div>

<script type="text/javascript" src="prototype.js"></script>
<script>
 function getS() {
var params = 'query=' + $F('input_test_form_text');
var x = new Ajax.Updater('searchresults', '/ajax_search.jsp',
{method: 'get',parameters: params});
 }
</script>
The follow is a trivial server side JSP ajax_search.jsp that does nothing but returns the original query as an HTML snippet:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
String req = request.getParameter("query");
out.println("<p>request for 'query' is:" + req + "</p>");
%>

No comments: