Skip to content

banner ajax
The Complete Reference: Ajax

Examples: One-way Cookie

How do you feel about JavaScript?

Hate It - [ 1 2 3 4 5 ] - Love It

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Chapter 2 : Cookie Rating - One Way</title>
<script type="text/javascript">
 
 
function sendRequest(url,payload)
{
    for (var key in payload)
    document.cookie = key+"="+payload[key]+"; path=/; domain=ajaxref.com";
 
    window.location = url;
}
 
function readCookie(name)
     {
       var nameEQ = name + "=";
       var ca = document.cookie.split(';');
       for (var i=0;i < ca.length;i++)
         {
          var c = ca[i];
          while (c.charAt(0)==' ')
              c = c.substring(1,c.length);
          if (c.indexOf(nameEQ) == 0)
              return c.substring(nameEQ.length,c.length);
         }
       return null;
      }
 
function rate(rating)
{
    /* string identifying type of example making rating */
    var transport = "cookie";
 
    /* URL of server-side program to record rating */
    var url = "http://ajaxref.com/ch2/setrating.php";
 
    /* form payload object with rating and transport name/value pairs */
    var payload = {'rating':rating, 'transport':transport};
 
    /* submit rating  */
    sendRequest(url,payload);
 
    /* indicate vote was made */
    var resultDiv = document.getElementById("resultDiv");
    var ratingForm = document.getElementById("ratingForm");
    ratingForm.style.display = "none";
    resultDiv.innerHTML = "Thank you for voting.  You rated this question a " + rating + ".  You can see the ratings in the <a href='http://ajaxref.com/ch2/ratings.txt' target='_blank'>ratings file</a>.";
    resultDiv.style.display = "";
}
</script>
 
</head>
<body>
<h3>How do you feel about JavaScript?</h3>
<form action="http://ajaxref.com/ch2/setrating.php" method="get" id="ratingForm">
<em>Hate It - </em> [
<input type="radio" name="rating" value="1" onclick="rate(this.value);" /> 1
<input type="radio" name="rating" value="2" onclick="rate(this.value);"  /> 2
<input type="radio" name="rating" value="3" onclick="rate(this.value);" /> 3
<input type="radio" name="rating" value="4" onclick="rate(this.value);" /> 4
<input type="radio" name="rating" value="5" onclick="rate(this.value);"  /> 5
] <em> - Love It</em>
<noscript>
 <input type="hidden" name="transport" value="downgrade" />
 <input type="submit" value="Vote" />
</noscript>
 
</form>
<br />
<div style="display:none;" id="resultDiv">&nbsp;</div>
</body>
</html>