Tushar
Tushar

Reputation: 1123

How do i use the AJAX request in JSP

I have created a registration page in JSP and I wanted to validate it with AJAX. So far I have written a piece of code that creates a request object(AJAX).

validate.js

window.onload=initPage;

function initPage() {   
    document.getElementById("username").onblur = checkUsername;
    document.getElementById("register").disabled = true;    
}

function createRequest() {
    try {
        request = new XMLHttpRequest();
    } catch (tryMS) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (otherMS) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = null;
            }
        }
    }   
    return request;
}

function checkUsername() {
    document.getElementById("username").className="thinking";
    request=createRequest();
    if(request==null)
        alert("Unable To Fetch Request");
    else
    {
        var name=document.getElementById("username").value;
        var userName=escape(name);
        var url="checkName.jsp?username="+userName;
        request.onreadystatechange=showUserNameStatus;
        request.open("GET", url, true);
        request.send(null);
    }   
}

The problem that I'm into is the url. I don't know how to validate that username in checkName.jsp. Actually the scenario is if the userName is validated then user can register himself and if the username is already registered, then server should force the user to choose different username.

function showUserNameStatus() {
    if(request.readyState==4)
    {
        if(request.status==200)
        {
            if(request.responseText=="okay")
            {
                document.getElementById("username").className="approved";
                document.getElementById("register").disabled = false;
            }
            else
            {
                document.getElementById("username").className = "denied";
                document.getElementById("username").focus();
                document.getElementById("register").disabled = true;
            }
        }
    }
}

Upvotes: 0

Views: 163

Answers (1)

Amar
Amar

Reputation: 971

If I understand, you have a registration page jsp , in which you are posting an AJAX call to validate the user , if the user is valid then you want to go ahead else you would like to throw back stating the user is already present ,choose a new one .

Instead of posting a call to the jsp ,what I will suggest is you can post the same to a servlet/controller/action class (whichever standard framework you are referring to) and then return back the response to the ajax call.

Upvotes: 1

Related Questions