I am trying to make AJAX call from html file to a servlet class to pass a variable but not getting any output. Please check the code below and suggest the changes that should be done.
FrontPage.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function func() {
var build = document.getElementById('name').textContent;
$.ajax({
type : 'GET',
url : 'http://localhost:8081/Sample/TestServlet',
data : build,
success : function(data) {
alert("Success");
},
error : function() {
alert("Error");
}
});
}
</script>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a id="name" href="#" onClick="func();">Build1</a>
</body>
</html>
This is TestServlet.java. This is trying to print variable which is passed from javascript function using Ajax call:
package com.infy;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println(request.getParameter("build"));
}
}
Web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Sample</display-name>
<welcome-file-list>
<welcome-file>FrontPage.html</welcome-file>
</welcome-file-list>
<servlet>
<description>Sample Servlet</description>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.infy.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>
I want to send the build variable to the servlet class and print the same from the servlet class but not getting any output.Please help me in fixing this.
out.println(request.getParameter("build"));will send back the data to ajax call and not print it.if ajax call is not hitting servlet change url to/TestServlet