
Papermashup.comより、PHPとjQueryで作るボックスのドラッグ&ドロップの紹介です。
HTMLのマークアップはごく普通にul要素を使ってボックスを作っています。下記のようなPHPのコードを含んだソースになります。
HTML PHP
<div id="list"> <div id="response"> </div> <ul> <?php include("connect.php"); $query = "SELECT id, text FROM dragdrop ORDER BY listorder ASC"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $id = stripslashes($row['id']); $text = stripslashes($row['text']); ?> <li id="arrayorder_<?php echo $id;?>"><?php echo $id;?> <?php echo $text;?> <div class="clear"></div> </li> <?php } ?> </ul> </div>
データベース用のPHPです、ボックスを入れ替えたときにデータベースを書き換えるスクリプトです。
PHP
<?php include("connect.php"); $array = $_POST['arrayorder']; if ($_POST['update'] == "update"){ $count = 1; foreach ($array as $idval) { $query = "UPDATE dragdrop SET listorder = " . $count . " WHERE id = " . $idval; mysql_query($query) or die('Error, insert query failed'); $count ++; } echo 'All saved! refresh the page to see the changes'; } ?> <?php include("connect.php"); $array = $_POST['arrayorder']; if ($_POST['update'] == "update"){ $count = 1; foreach ($array as $idval) { $query = "UPDATE dragdrop SET listorder = " . $count . " WHERE id = " . $idval; mysql_query($query) or die('Error, insert query failed'); $count ++; } echo 'All saved! refresh the page to see the changes'; } ?>
ボックスをドラッグ&ドロップさせるスクリプトです。jQueryで実現できます。
jQuery
$(document).ready(function(){ function slideout(){ setTimeout(function(){ $("#response").slideUp("slow", function () { }); }, 2000);} $("#response").hide(); $(function() { $("#list ul").sortable({ opacity: 0.8, cursor: 'move', update: function() { var order = $(this).sortable("serialize") + '&update=update'; $.post("updateList.php", order, function(theResponse){ $("#response").html(theResponse); $("#response").slideDown('slow'); slideout(); }); } }); }); });
コメント