Drag and Drop autosave and autoupdate

Discussion in 'JavaScript' started by Gainax, Apr 18, 2008.

  1. #1
    Hi

    I have created a drag and drop application whereby users who view it are able to drag and drop a series of rows, edit them and then click 'save' which saves the row information to a txt file.

    What I'm looking to do is, make it so that everytime a user drags and drops a particular row, the information is saved dynamically, possibly to a database, rather than a txt file, without the need to click on the save button.

    As the application is a table, with 5 columns, the final column, is to be a number (from 1 > n).
    What I'm looking to do is, when a user drags, lets say row 1 and drops it to replace row 3, I want to dynamically update the numbers.

    Example

    A - B - C - 1
    D - E - F - 2
    G - H - I -3

    So when row one is moved, currently on my version it reads:

    D - E - F - 2
    G - H - I -3
    A - B - C - 1

    What i want it to read is:

    D - E - F - 1
    G - H - I -2
    A - B - C - 3


    My code is as follows:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    	<head>
    		<title>ABA Priority List</title>
    		<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    		<script type="text/javascript" src="js/sort.js">
    		</script>
    		<link rel="stylesheet" type="text/css" href="styles/styles.css" />
    		<script type="text/javascript">
    			//------------------------------
    			//Custom Info
    			var colNames=new Array
    			(
    				"Briefed by:",
    				"DIGITAL",
    				"Needed by:",
    				"STATUS",
    				"PRIORITY"
    			);
    
    			var defaultCellText="-";
    			//--------------------------------
    			//--------------------------------
    
    			var sortObj=null;
    			window.addEvent("domready",function()
    			{
    				sortObj=new Sortables($('TableList'));
    
    				$("AddButton").addEvent("click",function()
    				{
    					addRow();
    				});
    
    				$("SaveButton").addEvent("click",function()
    				{
    					save();
    				});
    
    				$("SortRadio").addEvent("click",function()
    				{
    					sortMode();
    				});
    
    				$("EditRadio").addEvent("click",function()
    				{
    					editMode();
    				});
    
    				$("RevertButton").addEvent("click",function(){
    					revert();
    				});
    
    				$$("#Controls form")[0].reset();
    
    				if(!window.ie)
    					$("TableList").setStyle("margin-left","110px");
    
    				getDataFromServer();
    			});
    
    			function getRow(datArray)
    			{
    				var info=new Array(defaultCellText,defaultCellText,defaultCellText,defaultCellText,defaultCellText);
    				if(typeof datArray !== "undefined")
    				{
    					info=datArray;
    				}
    
    				var row=maker("li").addClass("rowItem unsaved");
    
    				row.appendChild(maker("p").addClass("cellP close").setHTML('<img src="images/close.png" class="x" alt="[x]" />').addEvent("click",function()
    				{
    							this.parentNode.remove();
    						}
    					)
    				);
    
    				for(var i=0;i<5;i++){
    					row.appendChild(maker("p").addClass("cellP col"+(i+1)).setHTML('<input type="text" value="'+info[i]+'" />'));
    				}
    
    				return row;
    			}
    
    			function addRow(datArray)
    			{
    				$("TableList").appendChild(getRow(datArray));
    				sortObj.detach();
    				sortObj=null;
    				sortObj=new Sortables($('TableList'));
    				$$(".rowItem .close .x").setStyle("display","inline");
    				$("SortRadio").click();
    
    			}
    
    			function maker(tag){
    				return $(document.createElement(tag));
    			}
    
    			function save()
    			{
    				var args=getDataFromForm();
    
    				var myAjax = new Ajax("data/save.php",
    				{
    						data: "data="+args,
    						method: 'post',
    						onRequest:function(){
    							$("Status").setHTML("<span>Saving</span>");
    						},
    						onComplete:function(response)
    						{
    							alert(response);
    							if(response=="Data saved")
    							{
    								var d=new Date();
    								$("Status").setText("Last save: "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
    								$$("#TableList .rowItem").removeClass("unsaved");
    								$$("#TableList .rowItem").addClass("saved");
    							}
    						}
    					}
    				);
    				myAjax.request();
    			}
    
    			function editMode()
    			{
    				sortObj.detach();
    				$$(".rowItem .close .x").setStyle("display","inline");
    				$$("#TableList input").setStyle("background","white");
    			}
    
    			function sortMode()
    			{
    				sortObj.attach();
    				$$(".rowItem .close .x").setStyle("display","none");
    				$$("#TableList input").setStyle("background","transparent");
    			}
    
    			function revert()
    			{
    				if(!confirm("Are you sure you want to revert to the last saved state?"))
    					return;
    				getDataFromServer();
    			}
    
    			function getDataFromServer(){
    				var myAjax = new Ajax("data/load.php",
    				{
    						method: 'get',
    						onRequest:function()
    						{
    							$("Status").setHTML("<span>Loading</span>");
    						},
    						onComplete:function(response)
    						{
    							var data=eval(response);
    							if(typeof response.length !=="undefined")
    							{
    								$("TableList").setHTML('');
    								for(var i=0;i<data.length;i++)
    								{
    									addRow(data[i]);
    								}
    								$("Status").setText("");
    								$$("#TableList .rowItem").removeClass("unsaved");
    								$$("#TableList .rowItem").addClass("saved");
    							}
    						}
    					}
    				);
    				myAjax.request();
    			}
    
    			function getDataFromForm()
    			{
    				var rows=$$("#TableList li");
    				var str="";
    
    				for(var i=0;i<rows.length;i++)
    				{
    					var cols=rows[i].getElements("input");
    					var colstr="";
    					for(var j=0;j<cols.length;j++)
    					{
    						if(j!=0)
    							colstr+=',';
    						colstr+='"'+encodeURIComponent(hEsc(cols[j].value))+'"';
    					}
    					str+=colstr+"\n";
    				}
    
    				return str;
    			}
    
    			function hEsc(str)
    			{
    				var targ=str;
    
    				targ=targ.replace(/'/g,"'");
    				targ=targ.replace(/"/g,"&quot;");
    				targ=targ.replace(/</g,"&lt;");
    				targ=targ.replace(/</g,"&gt;");
    
    				return targ;
    			}
    		</script>
    	</head>
    	<body>
    	<div id="wrapper">
    	<h1>ABA Priority List - <?php echo date('l jS F Y'); ?></h1>
    
    		<div id="DataDiv">
    			<div id="OuterControls">
    				<div id="Controls">
    					<input type="image" src="images/button.jpg" name="AddRow" width="90" height="22" id="AddButton" value="AddRow" STYLE="margin: 5px;">
    					<form onsubmit="return false" method="post" action="#">
    					<p>
    						<input type="radio" id="SortRadio" value="sort" name="mode" checked="checked" STYLE="margin-left: 5px; "/> Sort mode
    					</p>
    					<p>
    						<input type="radio" id="EditRadio" value="sort" name="mode" STYLE="margin-left: 5px; " /> Edit mode
    					</p>
    				</form>
    				<input type="image" src="images/save.jpg" name="SaveButton" width="41" height="17" id="SaveButton" value="SaveButton" STYLE="margin-left: 3px; margin-top: 5px;float: left;">
    				<input type="image" src="images/revert.jpg" name="Revertbutton" width="49" height="17" id="RevertButton" value="RevertButton" STYLE="margin-left: 1px; margin-right: 3px; margin-top: 5px; float: right;">
    
    				<br /><br />
    				<p class="saved2">
    				<span class="inside">Saved</span>
    				</p>
    				<p class="unsaved2">
    					<span class="inside">Unsaved</span>
    				</p>
    				<p id="Status">
    				</p>
    			</div>
    				</div>
    
    			<li class="rowItem header">
    				<p class="cellP close"></p>
    				<p class="cellP col1"><script>document.write(colNames[0])</script></p>
    				<p class="cellP col2"><script>document.write(colNames[1])</script></p>
    				<p class="cellP col3"><script>document.write(colNames[2])</script></p>
    				<p class="cellP col4"><script>document.write(colNames[3])</script></p>
    				<p class="cellP col5"><script>document.write(colNames[4])</script></p>
    			</li>
    			<ul id="TableList">
    				<span>Loading saved data</span>
    
    			</ul>
    		</div>
    			</div>
    	</body>
    </html>
    Code (markup):
    The save script is here:

    <?php
    
    	$logfilename="data.txt";
    
    	if(empty($_POST["data"])||!isset($_POST["data"])){
    		echo "No data given";
    		exit;
    	}
    
    	$data=explode("\\n",stripslashes($_POST["data"]));
    
    	$file=fopen($logfilename,'w');
    
    	foreach($data as $d){
    		fwrite($file,"$d\n");
    	}
    	fclose($file);
    
    	echo "Data saved";
    
    ?>
    PHP:
    And the load script is here:

    <?php
    
    	$logfilename="data.txt";
    
    	if(file_exists($logfilename))
    		$data=file_get_contents($logfilename);
    	else{
    		echo '[["","","","",""]]';
    		exit;
    	}
    
    	$lines=explode("\n",$data);
    
    	echo "[";
    	foreach($lines as $k=>$l){
    		if(!empty($l)){
    			if($k!=0)
    				echo ",";
    			echo "[";
    				$cells=explode(',',$l);
    				foreach($cells as $j=>$c){
    					if($j!=0)
    						echo ",";
    					echo $c;
    				}
    			echo "]";
    		}
    	}
    	echo "]";
    
    ?>
    PHP:
    All help appreciated.
     
    Gainax, Apr 18, 2008 IP