Highlight and Record AJAX Widget

javascript, jquery, php, sql

This is JavaScript code used with the jQuery framework so that when a user highlights a section of text on the page that you store what they highlighted. The jQuery code is below and the PHP is below that. Simple.

				/* attempt to find a text selection */
				function getSelected()
				{
					if(window.getSelection)
					{
						return window.getSelection();
					}
					else if(document.getSelection)
					{
						return document.getSelection();
					}
					else
					{
						var selection = document.selection && document.selection.createRange();
						
						if(selection.text)
						{
							return selection.text;
						}
						return false;
					}
					return false;
				}

				/* create sniffer */
				$(document).ready(function() {
					$('#content-area').mouseup(function(){
						var selection = getSelected();
						
						if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,'')))
						{
							$.ajax({
								type: 'post',
								url: 'ajax-selection-copy.php',
								data: 'selection=' + encodeURI(selection)
							});
						}
					});
				});
			
				if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && $selection = trim($_POST['selection']))
				{
					mysql_query('INSERT INTO text_selections (selection,date_selected) VALUES(\''.mysql_escape_string(stripslashes($selection)).'\',NOW())');
				}