Fisher Man
Fisher Man

Reputation: 487

JavaScript Comparision fails, when retrieving the values from the Servlet through ajax

Using the function storeSessionId() , I retrieved the value of storedSession and assigned to sessionId from the servlet using AJAX.

   var storedSession;
   var sessionId;       

function storeSessionId(){
    try
    {
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                storedSession = xmlhttp.responseText.toString();
                sessionIdValue(storedSession);

            }
        };
        xmlhttp.open("POST","JoinAction?subject="+subject+"&userId="+userId+"&secureKey="+secureKey,true);
        xmlhttp.send();
    }
    catch(err)
    {
        alert(err.description);
    }
}

When I compared the sessionId!=null only my div will be displayed else it cannot be displayed.

But even if I got sessionId==null also, my div was displayed. My div was displayed in both the condition.

function sessionIdValue(storedSession){
    sessionId = storedSession;
    if(sessionId != null && sessionId != "null"){
        document.getElementById("div").style.display="inline";
    }
}

Upvotes: 1

Views: 75

Answers (3)

Fisher Man
Fisher Man

Reputation: 487

The solution is ,

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}

I passed the sessionId value in to trim()...

Thanks for all who helped me..

Upvotes: 0

Hardik Mishra
Hardik Mishra

Reputation: 14887

You are comparing sessionId != null which is incorrect.

Put alert(sessionId) to know the response value.

Try:

if(sessionId && sessionId != "null"){
 document.getElementById("div").style.display="inline";
}

First condition checks whether sessionId is not undefined and then for null string.

Upvotes: 0

slashnick
slashnick

Reputation: 26549

Most likely sessionId is an empty string "". Try changing the condition to

if(sessionId && sessionId != "null")

This will just check for a truthy value which the empty string is not.

Upvotes: 1

Related Questions