1

I have a registration form where I am validating the "preferred login id" using AJAX so it searches the users table and shows if it's available or not, and it displays next to the text box "username available" or "username not available".

My requirement is when it's not available I want to pass the text "username not available" back to the javascript in the JSP from the Servlet so that I can stop the user from proceeding the form. I believe I can do it using AJAX. But I dont know how to do it. Could someone help me on this with the code?

2 Answers 2

2

I would use JQuery, and the get() method in particular as an example

Here is a pseudo solution (didn't test it, but it's the basic approach I would use)

JavaScript

var userIsAvailable = false;
function checkUsernameAvailability(userIdToCheck){
    $.get("pathToServlet",{userId: userIdToCheck},function(resultMessage){
         userIsAvailable = resultMessage=="username available" //this is bad practice, just an example, pass true/false      
         $("#userAvailabilityMessage").text(resultMessage);
    }
 });

HTML

<form onsubmit="if(!userIsAvailable){alert('user is not available')}; return userIsAvailable">
    <label for="userId">preferred login id<label>
    <input id="userId" ... type="text" onblur="checkUsernameAvailability(this.value)"> 
    <div id="userAvailabilityMessage" />
    ...
</form>

Servlet (partial)

@WebServlet("/pathToServlet")
public class MyServlet extends HttpServlet {
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String result;

            if(isUserNameAvailable(request.getParameter("userId"))){
                  result = "username available";
            }else{
                  result = "username not available";
            }
            response.setContentType("text/plain");
            response.getWriter().print(result);
     }

}
Sign up to request clarification or add additional context in comments.

5 Comments

dear friend, i am getting the availability properly. If the username is not available it does display that message. Now even if it displays that message and still user tries to submit it should not allow. So what my idea of implementing it is get the text displayed in the div and if the text is "username is not available" it should return false and not forward. But it is not working.
var tt=document.getElementById("invlist"); var myDiv = tt.firstChild; var myText = myDiv.data; var test="This investor already exists"; if(myText==test){ alert(test); return false }
i tried ur solution. it gives me only one alert saying username is not available :(
try to debug it, userIsAvailable should be true if user is available. to check, just hard code userIsAvailable to true, and the form should submit. if you pass this, then just make sure that userIsAvailable gets the correct value...
i tried voting up several times..but it says i need atleast 15 reputations for voting up..
0

You need to send object with some flag in message. You can use json for this. On servlet side:

// This object we will transfere from java to javascript
public class Message {
    private boolean error;
    private String errorMessage;

    // Getters and setters ommited
}

// Servlet code - return content

Message message = new Message();
message.setError(true);
message.setErrorMessage("Your error message");
Gson gson = new Gson(); // GSON - java json library from Google. I prefer it
String content = gson.toJson(message);
response.setContentType("text/json");
response.getWriter().print(content);

And finally javascript code:

function processRequest() {
    var result = jQuery.ajax ({
        url: "your.url",
        method: "post",
        async: false,
        data: "your=data&andsomedate=somedata"
    });

    // Creating object from json
    var message = jQuery.parseJSON(result.responseText);

    // Now we can access all object fields:
    if(message.error) {
        alert("Error message: " + message.errorMessage);
    }
}

1 Comment

This is by far not the way to get a JSON object from the server, use getJSON instead... api.jquery.com/jQuery.getJSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.