amir zaghari
amir zaghari

Reputation: 89

Store position of multiple draggable items in database

I have some draggable elements in my html

<div class="box-body">
<div id="1" class="draggable ui-widget-content ui-draggable ui-draggable-handle" style="top:200px; left:80px;">
<div id="2" class="draggable ui-widget-content ui-draggable ui-draggable-handle" style="top:200px; left:100px;">
<div id="3" class="draggable ui-widget-content ui-draggable ui-draggable-handle" style="top:200px; left:120px;">
</div>

and my scripts :

$( ".draggable" ).draggable({ containment: ".box-body", scroll: true }); 

$( document ).ready(function() {
    $('.box-body').slimscroll({
        alwaysVisible : true,
        axis: 'both',
        height: '500px',
        width: '100%',
        railVisible: true,
      });        
});

How should I generate multiple post/get requests (after movements) to store div positions in my database? some thing like this:

http://myURL/racks/id=divID&top=topValue&left=leftValue

I found some codes like this fiddle : http://jsfiddle.net/CAEV5/9/ But I should batch update all div position in my database!!

Upvotes: 0

Views: 230

Answers (1)

Twisty
Twisty

Reputation: 30883

From your fiddle, I would suggest something like this:

$(function() {
  function recordPos(el, pos) {
    var id = el.data("need");
    $.ajax({
      type: "POST",
      url: "your_php_script.php",
      data: {
        x: pos.left,
        y: pos.top,
        need_id: id
      },
      success: function(msg) {
        console.log("Data saved for ", el[0], pos);
      }
    });
  }
  $("#set div").draggable({
    stack: "#set div",
    stop: function(event, ui) {
      //Do the ajax call to the server
      recordPos($(this), ui.offset);
    }
  }).each(function() {
    recordPos($(this), $(this).offset());
  });
});

http://jsfiddle.net/Twisty/CAEV5/320/

Creating a function allows us to repeat the same process many times. We call it when an item stops and for each of the items upon initialization. SSo in case a user does not move any of the items, and only moves 1, you know the position of all the items when the page loads.

Upvotes: 1

Related Questions