Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 25th, 2012  |  syntax: None  |  size: 1.32 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to get jQuery, AJAX and a servlet working together?
  2. $(document).ready(function() {
  3.         $("a").click(function(){
  4.             alert("Should be going to servlet now");
  5.             $.ajax({
  6.                 type: 'GET',
  7.                 url: "checkName",
  8.                 data: {userName: "Hexose"},
  9.                 success: function(data){ alert(data);}
  10.             });
  11.         });
  12.  
  13.     });
  14.        
  15. public class CheckUserNameServlet extends HttpServlet {
  16.  
  17. protected void doGet(HttpServletRequest request,
  18.         HttpServletResponse response)
  19.         throws ServletException, IOException {
  20.  
  21.     String targetUN = request.getParameter("userName");
  22.  
  23.     if (data.UserDB.userNameExists(targetUN)) {
  24.         String exists = "Username already taken...";
  25.         response.setContentType("text");
  26.         response.setHeader("Cache-Control", "no-cache");
  27.         response.getWriter().write(exists);
  28.         response.setStatus(200);
  29.     } else {
  30.         response.getWriter().write("Username is available...");
  31.     }
  32. }
  33.        
  34. <tr>
  35.   <td align="right">Username:</td>
  36.   <td><input type="text" name="userName" id="userName" value="${user.userName}"  /</td>
  37.   <td><span id="exist"> <a href="">Check Availability</a></span></td>
  38. </tr>
  39.        
  40. $("#exist a").click(........
  41.        
  42. $("a").click(function(e){
  43.     e.preventDefault();
  44.     ...........
  45.        
  46. $("#userName").val()