views:

631

answers:

1

I am trying to call a servlet from jQuery's .ajax() function.

At the moment I don't think I am even calling the servlet or passing paramaters to it, however lots of Googling doesn't seem to have helped. Any ideas?

This is my html:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function login(){

$("#loading").hide();

var email = document.nameForm.email.value;
$.ajax({
type: "GET",
url: "ProcessForm",
data: "email="+email,
success: function(result){
alert(result); }
});
}
My AJAX

This time it's gonna work

Email loading

</body>
</html>

And my web.xml

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>ajaxtry</display-name>
  <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
<servlet-name>ProcessForm</servlet-name>
<servlet-class>com.ajaxtry.web.ProcesFormServlet</servlet-class>
  </servlet>
   <servlet-mapping>
<servlet-name>ProcessForm</servlet-name>
<url-pattern>/ProcessForm</url-pattern>
  </servlet-mapping>
</web-app>

The servlet is just a template at the moment:

package com.ajaxtry.web;

// imports here

public class ProcessFormServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

response.setContentType("text/html"); PrintWriter out = response.getWriter();

System.out.println(request.getParameter("email")); } }

+3  A: 

A couple of problems here:

You're calling System.out.println, which is just sending output to standard out - not to the browser. Try changing "System.out.println" to just "out.println"

It looks like you've defined doPost() in your servlet code, but your javascript is using the "GET" method. Rename doPost() to doGet(), or define both of them.

That being said, you probably shouldn't bother with the javascript at all until you've actually got the servlet working, to keep it simple. You should be able to test it by loading /ProcessForm?email=testing in your browser and see some output. Once you get that going, then you can start worrying about the front-end code.

Hope this helps get you started.

mpobrien
Thanks, I had already done the first two things, the second is a good suggestion, I think that will be the way to go.
Ankur
I mean the third, the second is an obvious mistake ;)
Ankur