How to get jQuery, AJAX and servlet working together?

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?

+4
source share
3 answers

1. jQuery ajax ()

In JavaScript, you cannot create new threads - closest you can use setTimeout() or setInterval() . This means that operations that take a lot of time (for example, fetching data over a network) will block everything else. That way, you'll often use callback functions (this exploits the fact that functions are first-class members in JavaScript).

The success parameter for the ajax() function is that the callback function that will be called when the request completes successfully is default, the ajax requests are asynchronous, so you need to hook something to let them know when the action is completed . Think of it as registering a listener with Swing if you have ever used it. The success function will be called with certain arguments (remember that JavaScript supports var-args), the first of which is the data received as an answer. If jQuery can correctly identify the data type (or if you set the dataType parameter in the ajax() call), data will be the parsed response available for use.

The shortcut that can be used in this case is jQuery get() - it uses ajax() internally, but gives a simpler call function to make GET requests

In addition, as others have noted, you should attach your click event handler to more specific elements and a elements, it is usually recommended to prevent the default ( event.preventDefault() ) so that the browser does not follow the link.

You might want to use Firebug for Firefox - it provides a console object where you can write data - console.log("Response: ", data) will print the contents of the data to the console, and if it is an object (for example, a JSON response) it’s even will look hierarchical that you can explore. This is much better than the alert() bundle, which blocks execution until you click ok and are less annoying.

2. Servlet

Why do you think there is a problem? Your servlet looks great, with the possible exception of some unnecessary things (for example, to set the status code to 200). In addition, you may need to change the content type to text/plain , which is the regular MIME type for plain text. Later, you could look into JSON and send a JSON response so that you can add additional information to your response (for example, suggested usernames when the requested username is not available) in a structured way that can be easily used by client-side JavaScript.

3. Getting the value of the text field

It also looks great - $("#userName").val() . You can use Firebug to examine the current DOM and see why the value of the text field is set. You have one problem with your code, but I'm not sure if you made a mistake by pasting it here or if this is really a problem in the code. You are missing a closing bracket > before </td>

<td><input type="text" name="userName" id="userName" value="${user.userName}" /</td>

+2
source
  • Your jquery seems correct, although you probably did not want to attach the same click handler to all the bindings on your page. :) The way you use jquery for ajax calls is just fine. There are many situations in which you want to receive json as a response from the server, in which case you will use the parameter: dataType: "json" , and the data parameter that comes to the successful handler will be a javascript object (if you configured it correctly the type of response in the servlet with something like: response.setContentType("application/json");

  • Try using firebug to see if you are actually making a call to the server, and to see what you get from it. (since you said this works when you try to use it in a browser)

  • $('#userName").val() should work. But I'm not sure if you initialize the value ${user.userName} that you use to fill the value in this field. Have you tried to fill in the field yourself?

+1
source

Firstly, a possible problem: you add the jQuery .click() handler to the ALL <a ....></a> anchor tags, in this case a much better way would be to listen to the anchor tags inside the exist span:

 $("#exist a").click(........ 

Secondly, with your jQuery you are not telling the browser not to do what it should do. I mean, if someone clicks on the anchor tag, the browser understands that it must follow it - an empty href reload the page.
This action can be stopped very easily:

 $("a").click(function(e){ e.preventDefault(); ........... 

As for data success, this is what is passed to the function when the ajax call returns. It can be a lot, text , html or json . Therefore, in the case of your servlet, it looks like text, and it should be either Username already taken... or Username is available...

This is correct for getting the value of your input field, but it looks like if you copied and pasted your HTML code, you were unable to close > from your input field for userName

 $("#userName").val() 
+1
source

Source: https://habr.com/ru/post/1345433/


All Articles