Archive for March, 2006

JavaScript Cookies

JavaScript Cookies

If like me you usually create your cookies using a server scripting language like PHP, you may find that using JavaScript for cookies is simple.

Im going to show you how to create, edit, delete and read cookies using only JavaScript.

Creating JavaScript Cookies:

function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

As you can see the function createCookie requires 3 values:


  • name = the name you want to give the cookie

  • value = the value the cookie will hold

  • days = the number of days you want the cookie to last [can be up to 30 days])

Deleting a JavaScript Cookie:

function eraseCookie(name) {
  createCookie(name, "", -1);
}

The above function eraseCookie requires the name of the cookie you want to delete. It simply marks the expire date as yesterday.

Reading a JavaScript Cookie:

function readCookie(name) {
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return "";
}

readCookie does just that, provide the function with the name of the cookie you want to read and it will return its value.

So lets put all that together now and write the contents of the cookie out to the screen.

<HTML>
 <HEAD>
  <TITLE>JavaScript Cookies</TITLE>
<script language="JavaScript">
function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
  createCookie(name, "", -1);
}

function readCookie(name) {
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return "";
}

function makeCookie() {
 createCookie("test_cookie", "This is the contents of my cookie", 3);
 document.getElementById("my_cookie").innerHTML = readCookie("test_cookie");
}

function editCookie() {
 eraseCookie("test_cookie");
 createCookie("test_cookie", "This is the edited content of the cookie now!!!", 3);
 document.getElementById("my_cookie").innerHTML = readCookie("test_cookie");
}
</script>
  </HEAD>
   <BODY onLoad="makeCookie()">
   <span id="my_cookie"></span><br />
   <a href="#" onClick="editCookie()">Change value</a><br />
   </BODY>
</HTML>

In the above code we simply create the cookie using body onLoad and calling the makeCookie() function.
When we click the link ‘Change Value’ we are calling the JavaScript function editCookie() which deletes the current cookie and recreates a new one with the same name but new value.

That’s all there is to it, easy peasy!! :-)

Comments (1)

Simple Ajax Functions - Snippets

Basic Ajax Functions
I’ve created a list of very common JavaScript functions for Ajax. They have been created in quick reference fashion and do not contain any fancy stuff. Instead of creating one function which can handle various tasks depending on passed values, they are split into seperate basic task functions. The reason for this is simplicity.

Anyway - here they are. I’ll post the function and give a basic outline of what it does.

This first function is the real important one - it’s the one which creates the object for making the Ajax connection.

<script type="text/javascript">
<!--
	var http = createRequestObject();

	function createRequestObject() {
		var xmlhttp;
		try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }
	  catch(e) {
	    try { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	    catch(f) { xmlhttp=null; }
	  }
	  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
	  	xmlhttp=new XMLHttpRequest();
	  }
		return  xmlhttp;
	}
 // -->
</script>

Here is the function which sends the request to the server script. This version creats the connection with TEXT and uses the POST method.

<script type="text/javascript">
<!--
	function sendRequestTextPost() {
	var rnd = Math.random();
	var myvalue1 = escape(document.getElementById("myvalue1").value);
	var myvalue2 = escape(document.getElementById("myvalue2").value);
	try{
    http.open('POST',  'serverscript.php');
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.onreadystatechange = handleResponseText;
		http.send('myvalue1='+myvalue1+'&myvalue2='+myvalue2+'&rnd='+rnd);
	}
	catch(e){}
	finally{}
}
 // -->
</script>

Here is the function which sends the request to the server script. This version creats the connection with TEXT and uses the GET method.

<script type="text/javascript">
<!--
	function sendRequestTextGet() {
	var rnd = Math.random();
	var myvalue1 = escape(document.getElementById("myvalue1").value);
	var myvalue2 = escape(document.getElementById("myvalue2").value);
	try{
    http.open('GET',  'serverscript.php?myvalue1='+myvalue1+'&myvalue2='+myvalue2+'&rnd='+rnd);
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.onreadystatechange = handleResponseText;
		http.send(null);
	}
	catch(e){}
	finally{}
}
 // -->
</script>

Here is the function which sends the request to the server script. This version creats the connection with XML and uses the POST method.

<script type="text/javascript">
<!--
	function sendRequestXmlPost() {
	var rnd = Math.random();
	var myvalue1 = escape(document.getElementById("myvalue1").value);
	var myvalue2 = escape(document.getElementById("myvalue2").value);
	try{
    http.open('POST',  'serverscript.php');
    http.setRequestHeader('Content-Type', "text/xml");
    http.onreadystatechange = handleResponseXml;
		http.send('myvalue1='+myvalue1+'&myvalue2='+myvalue2+'&rnd='+rnd);
	}
	catch(e){}
	finally{}
}
 // -->
</script>

Here is the function which sends the request to the server script. This version creats the connection with XML and uses the GET method.

<script type="text/javascript">
<!--
	function sendRequestXmlGet() {
	var rnd = Math.random();
	var myvalue1 = escape(document.getElementById("myvalue1").value);
	var myvalue2 = escape(document.getElementById("myvalue2").value);
	try{
    http.open('GET',  'serverscript.php?myvalue1='+myvalue1+'&myvalue2='+myvalue2+'&rnd='+rnd);
    http.setRequestHeader('Content-Type', "text/xml");
    http.onreadystatechange = handleResponseXml;
		http.send(null);
	}
	catch(e){}
	finally{}
}
 // -->
</script>

Now here is the function which retrieves the response from the server script. This version receives the response as TEXT (http.responseText).

<script type="text/javascript">
<!--
function handleResponseText() {
	try{
    if((http.readyState == 4)&& (http.status == 200)){
    	var response = http.responseText;
      document.getElementById("idforresults").innerHTML = response;
		}
  }
	catch(e){alert("hello");}
	finally{}
}
 // -->
</script>

Now here is the function which retrieves the response from the server script. This version receives the response as XML (http.responseXML).

<script type="text/javascript">
<!--
function handleResponseXML() {
	try{
    if((http.readyState == 4)&& (http.status == 200)){
    	var response = http.responseXML.documentElement;
    	var response_value = response.getElementsByTagName('tagname')[0].firstChild.nodeValue;
    	document.getElementById("idforresults").innerHTML = response_value;
		}
  }
	catch(e){}
	finally{}
}
 // -->
</script>

This little function can be used to delay the call - handy for forms where you use onKeyUp or onKeyPress to trigger submit action.

<script type="text/javascript">
<!--
function keyUp() {
	window.setTimeout("sendRequest()", 400);
}
// -->
</script>

Below is just an example form which I used to work with the above functions.

<!-- BASIC WITH BUTTON PRESS -->
<form>
<label>My Value 1: <input type="text" name="myvalue1" id="myvalue1"></label><br />
<label>My Value 2: <input type="text" name="myvalue2" id="myvalue2"></label><br />
<input type="button" name="call" value="submit" onClick="sendRequestTextPost()">

Here is a basic one field worm which used the onKeyUp to trigger the Ajax with the delay.

<!-- BASIC WITH ON KEY PRESS -->
<!-- SHOULD PROBABLY ONLY BE USED WHEN ONE INPUT IS SUPPLIED -->
<label>My Value 1: <input type="text" id="myvalue" onkeyup="keyUp()"></label><br />
</form>

And finaly here is the element on the page which the Ajax response is writen to.

<span id="idforresults"></span>

To put all this together - just pick the first function (createRequestObject() [remember to include the var http.. part above it]). Select the SendRequest function you require and the handle Request which uses the same method. Then add your form and update the form ID’s (remember to have these matching in the javascript!). See the other posts for a full example of these scripts hanging together.

Comments (4)

· Next entries »