使用php保存Jquery可拖动DIV的位置

时间:2013-05-01 19:00:16

标签: php jquery html draggable

关于如何保存可拖动DIV的位置,有很多解决方案,但我没有发现任何有助于在php中使用While循环。

我有一个“需求”数据库,我想显示符合人员用户名和状态= inprogress的所有“需求”。这可能是1需要或1,000,000需求,具体取决于是否符合标准。

我想在移动时自动保存需要位置(DIV)。这可能吗?如果可以的话,我想使用SQL将值存储在数据库中。

这里我目前拥有的代码显示“需求”(div)


<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <style>
  #set div { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
  #set { clear:both; float:left; width: 368px; height: 120px; }
  p { clear:both; margin:0; padding:1em 0; }
  </style>


<script>
$(function() {
  $( "#set div" ).draggable({ 
    stack: "#set div" 
  });
});


</script>



<div id="set">

<?

$query = mysql_query("SELECT * FROM needs WHERE (needsusername='$username' OR workerusername='$username') AND status='inprogress'");


while ($rows = mysql_fetch_assoc($query)) {
$title = $rows['titleofneed'];
$status = $rows['status'];

echo "
<div class='ui-widget-content'>
$title<br>Status: $status<br>

</div>
";
}

?>
</div>

插入查询

$x_coord=$_POST["x"];
$y_coord=$_POST["y"];
$needid=$_POST["need_id"];

    //Setup our Query
    $sql = "UPDATE coords SET x_pos=$x_coord, y_pos=$y_coord WHERE needid = '$needid'";

    //Execute our Query
    if (mysql_query($sql)) {
          echo "success $x_coord $y_coord $needid";
         }
        else {
        die("Error updating Coords :".mysql_error());   
}

1 个答案:

答案 0 :(得分:7)

当元素到达新位置时,您可以使用draggable的stop事件来引起注意。然后你只需得到偏移量as described in the docs

假设你有这样的设置:

<div id="set">
    <div data-need="1"></div>
     <div data-need="2"></div>
     <div data-need="3"></div>
     <div data-need="4"></div>
     <div data-need="5"></div>
</div>

我使用了一个数据属性来存储“需要”的id,稍后你可以使用该id来存储数据库中“需要”的位置。

现在如前所述,使用stop事件向服务器发送ajax调用,其中包含需要的id以及它的x和y位置。请注意,这是屏幕的位置,因此如果您有不同的屏幕尺寸,您应该使用相对于具有所需位置的父容器的位置。

$(function() {
  $( "#set div" ).draggable({ 
    stack: "#set div",
      stop: function(event, ui) {
          var pos_x = ui.offset.left;
          var pos_y = ui.offset.top;
          var need = ui.helper.data("need");

          //Do the ajax call to the server
          $.ajax({
              type: "POST",
              url: "your_php_script.php",
              data: { x: pos_x, y: pos_y, need_id: need}
            }).done(function( msg ) {
              alert( "Data Saved: " + msg );
            }); 
      }
  });
});

这样,每当可拖动元素到达新位置时,e请求将被发送到your_php_script.php。在那个脚本中,您只需要获取post参数并将它们存储在数据库中。

a working fiddle,当然ajax请求不起作用,但你可以看到控制台中发生了什么。

相关问题