Ajax
Ajax is an acronym for Asynchronous Java Script and XML. Ajax is used to easily exchange data between servers and client side UI. Also it has the ability to update part of the page without submitting/ refreshing the pages.
In this tutorial, will see little advanced example, Ajax call using servlet and process the hashmap result.
Application Overview:
- Create a web page using html
- Create a select element
- load the select element value from the Servlet and process the hashmap result
Servlet Code
The servlet process the request and send the data as per the category received. The class com.google.gson.Gson class converts the hashmap object to json string.
AjaxServlet.java
package ajax;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
/**
* @author Sivaranjani D
*
*/
public class AjaxServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter po = response.getWriter();
String category = request.getParameter("category");
HashMap<String,String> foodList = new HashMap<String,String>();
if(category!=null && category.equalsIgnoreCase("Fruits")){
foodList.clear();
foodList.put("fruits1", "Apple");
foodList.put("fruits2", "Banana");
}else if(category!=null && category.equalsIgnoreCase("Vegetables")){
foodList.clear();
foodList.put("vegetables1", "Brinjal");
foodList.put("vegetables2", "Tomato");
}else{
foodList.clear();
foodList.put("no", "No category selected");
}
po.write(cerateJSON(foodList));
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
private String cerateJSON(HashMap<String, String> lessonList) {
Gson gson = new Gson();
String json = gson.toJson(lessonList);
return json;
}
}
HTML
There are totally two select boxes in this html page. The first one has the static list of categories like fruits and vegetables. The second select box loads vegetables/fruits based on the category selected.
[caption id="attachment_501" align="aligncenter" width="988"]

ajaxservletwithobject.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax With Servlet</title>
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min-1.10.2.js"></script>
<script language="javascript" type="text/javascript">
function loadsValuesFromServlet(category) {
var url = '/Ajax2/loadFromServlet?category=' + category;
var myAjax = new Ajax.Request(url, {
method : 'post',
onComplete : function(originalRequest) {
var result = originalRequest.responseText.evalJSON();
;
var $this = $('#foodItems');
$this.empty();
for ( var key in result) {
if (result.hasOwnProperty(key)) {
$this.append('<option value='+key+'>' + result[key]
+ '</option>');
}
}
}
});
}
</script>
</head>
<body>
<table>
<tr>
<td>Select Category</td>
<td><select name='category' id="category"
onchange="loadsValuesFromServlet(this.value)">
<option value='-1'>--Please Select--</option>
<option value='Fruits'>Fruits</option>
<option value='Vegetables'>Vegetables</option>
</select></td>
</tr>
<tr>
<td>Values loded from servlet:</td>
<td>
<div id='loadedData'>
<select name='foodItems' id="foodItems">
<option value='-1'>--Please Select--</option>
</select>
</div>
</td>
</tr>
</table>
</body>
</html>
Download full Application
Result
[caption id="attachment_517" align="aligncenter" width="770"]
