Save position of Jquery draggable DIVs using php

后端 未结 1 613
长情又很酷
长情又很酷 2021-02-11 07:30

There are a lot of solutions out there as to how to save the position of draggable DIVs but I haven\'t found any that will help with using a While loop in php.

I have a

相关标签:
1条回答
  • 2021-02-11 08:15

    You can use the stop event of draggable to get noticed when an element has reached a new position. Then you just have to get the offset as described in the docs.

    Assuming you have a setup like that:

    <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>
    

    I've used a data attribute to store the id of the "need", you can later on use that id to store the position of the "need" in the database.

    Now as mentioned before, use the stop event to send an ajax call to the server with the id of the need and the x and y postion of it. Be aware hat this is the position of the screen so if you have different screen sizes you should probably use positions relative to a parent container with a desired position.

    $(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 );
                }); 
          }
      });
    });
    

    This way every time a draggable element reaches a new positions e request will be sent to your_php_script.php. In that script you then only have to grab the post parameters and store them in the database.

    There is a working fiddle, of course the ajax request is not working but you can see whats going on in the console.

    0 讨论(0)
提交回复
热议问题