This question has been asked many a times. But i got the common answer i.e to send the response through response.getwriter().write("....")
inside servlet. But it is not the actual way of sending response through ajax. I want to update a <div>
through the response not the whole page. But I didn't find solution to this. My code is as follows :-
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<script src="jquery.js" ></script>
<form name="myForm" method="post" id="search" action="al">
<input type="text" name="fname"/>
<input type="submit" value="Search" id="button1"/>
</form>
<div id="some">
</div>
<script>
$("#myForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(response)
{
$("#some").text(response);
//console.log(response);
//data: return data from server
},
error: function(response)
{
//if fails
}
});e.preventDefault();});
});
</script>
</body>
</html>
AddressLocator.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=request.getParameter("fname");
//response.getWriter().println("abc.html");
//response.sendRedirect("getData");
URL oracle = new URL("https://maps.googleapis.com/maps/api/geocode/json?address="+name);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
response.getWriter().write(inputLine);
in.close();
}
Here, al is mapped to AddressLocator class. Please help...thanx in advance..