How to get Cookie value through Javascript and displaying it in DIV tag:
In some cases we may have our webpages with PHP and HTML pages. If we want to display “Welcome {$username} Logout” if user loggedin and “Welcome Login Register” for new users means we can use innerHTML in javascript to achieve our goal.
In above case “{$username}” will be link to user account page. “Register” will link to registration page. “Logout” link to logout page.
<SCRIPT>
function getCookie(Name) {
var search = Name + “=”
if (document.cookie.length > 0) { // if there are any cookies
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(”;”, offset)
// set index of end of cookie value
if (end == -1)
end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function doit()
{
c=getCookie(”user_name”);
if(c==undefined){
document.getElementById(”login_show”).style.display=”block”;
}
else
{
var sHTML=”Welcome: <a href=’myaccount.php’>”+uname+’</a>’;
sHTML =sHTML+” <a href=’logout.php’>Logout</a>”;
loggedin_show.innerHTML = sHTML;
}
return false;
}
</SCRIPT>
We can use the above SCRIPT tag within HEAD tag.
getCookie is used to get the cookie names “user_name”. In doit function we can check whether cookie is available. If yes We can assign “Welcome {username} Logout” value to “loggedin_show” DIV. Otherwise we can show “login_show” DIV.
We can call above doit() function as follows.
<body onload=”return doit();”>
login_show div is shown below.
<DIV id=”login_show” style=”display:none”>
Welcome: <a href=”index1.php” mce_href=”index1.php”>Login</a> <a href=”signup.php” mce_href=”signup.php”>Register</a>
</DIV>
