All pastes #2057693 Raw Edit

Stuff

public javascript v1 · immutable
#2057693 ·published 2011-05-13 02:25 UTC
rendered paste body
<!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>  <title>AJAX Note Demonstration</title>  <meta name="author" content="Greg Baatard" />  <meta name="description" content="This example uses a simple AJAX note-keeping application to demonstrate handling XML responses to requests." />  <script type="text/javascript">	//Create XHR objects for the three things we need to do - adding, showing and deleting notes	var xhrAdd = createXhrObject();	var xhrShow = createXhrObject();	var xhrDelete = createXhrObject();	//This function is called when the user presses the Save button to add a new note	function addNote()	{		xhrAdd.open('POST', 'note_server.php');		//This request uses POST, so we need to include the form data in the header of the request		//The form_content variable will contain the form data, using JavaScript's "escape" function to sanitise it		xhrAdd.setRequestHeader('Content-Type','application/x-www-form-urlencoded');		var form_content = 'note_title=' + escape(document.note_form.note_title.value) +						   '&note_content=' + escape(document.note_form.note_content.value) +						   '&note_type=' + escape(getRadioValue(document.note_form.note_type));		xhrAdd.onreadystatechange = function()		{			if (xhrAdd.readyState == 4 && xhrAdd.status == 200)			{				//If we receive response text of "Ok", reset the form and call showNotes to update the display of current notes				if (xhrAdd.responseText == 'Ok')				{					document.note_form.reset();					showNotes();				}				else					alert('Could note add note.');			}		}		//The form content is included when we send the request		xhrAdd.send(form_content);	}	//This function shows all current notes.  It is called when the page loads, and when the user adds or deletes a note	function showNotes()	{		xhrShow.open('GET', 'note_server.php?get_notes');		xhrShow.onreadystatechange = function()		{			if (xhrShow.readyState == 4 && xhrShow.status == 200)			{				//The response to this request is an XML document, which we save in xmlNotes				var xmlNotes = xhrShow.responseXML;				//note_div refers to the <div> in which our notes will be displayed, and note_div_content will contain its content				var note_div = document.getElementById('current_notes');				var note_div_content = '';				//All <note> elements in the document (and their content) are stored in the notes variable				var notes = xmlNotes.getElementsByTagName('note');				//For each note...				for (i = 0 ; i < notes.length; i++)				{					//Store the content of the <note> tag's id, time and type attributes into variables					var id = notes[i].getAttribute('id');					var time = notes[i].getAttribute('time');					var type = notes[i].getAttribute('type');					//Store the text of the note's <content> element into the content variable					var content = notes[i].childNodes[1].firstChild.nodeValue;					// Note:  Alternatively, you could use the following code to get the text of the <content>					// var content = notes[i].getElementsByTagName('content')[0].firstChild.nodeValue;					//Store the content of the note's <title> element into the title variable					//Since the <title> tag may be empty, we make sure that we only try to store it if it exists					if (notes[i].firstChild.hasChildNodes())						var title = notes[i].firstChild.firstChild.nodeValue;					else						var title = '';					// Note:  Alternatively, you could use the following code to get the text of the <title>					// if (notes[i].getElementsByTagName('title')[0].hasChildNodes())					//	var title = notes[i].getElementsByTagName('title')[0].firstChild.nodeValue;					// else					//	var title = '';					//Use the note type to determine the background colour that the note will have when displayed					if (type == 'Urgent')						var bgcol = '#F39E77';					else if (type == 'To Do')						var bgcol = '#89CA9D';					else						var bgcol = '#8DCFF4';					//Use the data that we have stored from the XML response to create a <div> containing the details of the note					note_div_content +=					'<div id="' + id + '" style="background-color: ' + bgcol + '">' +						'<span style="float: left; font-weight: bold;">' + title + '</span>' +						'<span style="float: right;">' + time + ' <span title="Delete Note!" style="cursor: pointer; font-weight: bold;" onClick="deleteNote(' + id + ')">[X]</span></span>' +						'<span class="content">' + content + '</span>' +						'<span style="float: right;">' + type + '</span>' +					'</div>';				}				//Display the notes in the <div>				note_div.innerHTML = note_div_content;			}		}		xhrShow.send(null);	}	//This function deletes a note.  It is called when the user presses the "[X]" on a note	function deleteNote(id)	{		//The request uses GET, and includes the id number of the note to be deleted		xhrDelete.open('GET', 'note_server.php?delete_note=' + id);		xhrDelete.onreadystatechange = function()		{		  if (xhrDelete.readyState == 4 && xhrDelete.status == 200)		  {			//If we receive response text of "Ok", call showNotes to update the display of current notes			if (xhrDelete.responseText == 'Ok')			{				showNotes();			}			else				alert('Could note delete note.');		  }		}		xhrDelete.send(null);	}	//Returns an XHR object - if it can't make one the normal way, it tries doing it via ActiveX	function createXhrObject()	{		if (window.XMLHttpRequest)			return new XMLHttpRequest();		else if (window.ActiveXObject)			return new ActiveXObject("Microsoft.XMLHTTP");	}	//Returns the value of the selected radio button in a group	//This function is used when adding a new note	function getRadioValue(radGroup)	{		for (i = 0; i < radGroup.length; i++)		{			if(radGroup[i].checked)				return radGroup[i].value;		}		return '';	}  </script>  <style type="text/css">    /*A bit of CSS is used to control the looks and layout of the page, and keep the code as clean as possible*/	body {font-family: sans-serif; font-size: small; margin: 10px;}	textarea {font-family: sans-serif; font-size: small;}	th {text-align: right;}	div#current_notes div {margin: 5px; width: 290px; height: 100px; border: 1px solid black; display: inline-block; padding: 4px;}	div#current_notes div span.content {font-size: 11px; display: block; clear: both; height: 70%; overflow: auto;}  </style> </head> <!-- When the page first loads, showNotes() is called to display the current notes --> <body onload="showNotes();">	<div style="float: right; width: 380px; margin: 5px; font-style: italic;  text-align: justify;">This page demonstrates handling XML responses to a HTTP request.  An XHR object is used to request the details of current notes from the server.  The response to this request is in XML format, which you can view by clicking <a href="note_server.php?get_notes" target="_blank">here</a>.  JavaScript properties and functions are used to process the XML and display it below.</div>	<!-- The form calls addNote() and then returns false, ensuring that it doesn't actually "submit"	     in the traditional sense, which would involve loading the page again -->	<form name="note_form" method="post" onsubmit="addNote(); return false;">	<!-- This table simply contains the form for adding a new note -->	<table style="border: 1px solid black; width: 420px; float: left; margin: 5px;">		<tr>			<th>Title:</th>			<td><input type="text" id="note_title" name="note_title" style="width: 350px;" /></td>		</tr>		<tr>			<th>Content:</th>			<td><textarea id="note_content" name="note_content" style="width: 350px; height: 40px; overflow: auto;"></textarea></td>		</tr>		<tr>			<th>Type: </th>			<td>				<label for="r1" style="padding-right: 10px;"><input type="radio" id="r1" name="note_type" value="General" checked="checked" /> General</label>				<label for="r2" style="padding-right: 10px;"><input type="radio" id="r2" name="note_type" value="Urgent" /> Urgent</label>				<label for="r3" style="padding-right: 10px;"><input type="radio" id="r3" name="note_type" value="To Do" /> To Do</label>				<input type="submit" value="Save" style="width: 60px; float: right; text-align: center;" />			</td>		</tr>	</table>	</form>	<!-- This is the <div> in which current notes are shown (see the showNotes() function) -->	<div id="current_notes" style="width: 100%; height: 100%; padding-top: 10px; clear: both;"></div> </body></html>