I am extremely new to jQuery and AJAX, however after 7 hours of reading tutorials and playing with code, I have a good understanding of how they work. This is what I am trying to accomplish ....
I have a web application that allows the user to register on the site. I would like the username they entered (on the registration page) to be checked asynchronously for existence in the database. It seems pretty straight forward, but I had no luck.
This is the jQuery I wrote ...
$(document).ready(function() { $("a").click(function(){ alert("Should be going to servlet now"); $.ajax({ type: 'GET', url: "checkName", data: {userName: "Hexose"}, success: function(data){ alert(data);} }); }); });
I am using static data right now for debugging purposes, as I am having another problem getting a value from a form field. I also really don't understand success: the functional part, what is βdataβ as a function parameter? Does this come in response?
Now I have a servlet mapped to "checkName" and the servlet is working (I debugged and passed the parameter to the URL). Here is the servlet code ...
public class CheckUserNameServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String targetUN = request.getParameter("userName"); if (data.UserDB.userNameExists(targetUN)) { String exists = "Username already taken..."; response.setContentType("text"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(exists); response.setStatus(200); } else { response.getWriter().write("Username is available..."); } }
}
I know that my call to the database returns what I need, but I suspect that something in this servlet is wrong. And for good measure, there is an element from which it is assumed that the data comes from
<tr> <td align="right">Username:</td> <td><input type="text" name="userName" id="userName" value="${user.userName}" /</td> <td><span id="exist"> <a href="">Check Availability</a></span></td> </tr>
So, in fact, my questions ... 1. Am I using jQuery correctly using .ajax and what? Is there an easier way to do this or another method that is cleaner? 2. Is there something wrong with my servlet? I feel that the answer is incorrect, or I have encoded it incorrectly. 3. How do I get the value to form the userName element? I used $ ("# userName"). Val (), and it always gives an empty string or null.
Any pointers or tips or anything at this point will be greatly appreciated, as if Iβm losing my mind on this. Also, if I completely disconnect from this, feel free to just tell me a good tutorial.
Thanks in advance.
EDIT: So the identifier of the userName element was my problem. I changed the id and now everything works. However, one subsequent question. Is there a way to stop form submission if the response comes back and says the username is accepted?