Problem: I have a list of photos that I’ve uploaded.  I want to drag a photo from the pool of photos to a gallery or album.  So, basically I have two lists of items.  I’m dragging items from one list to the other list.  When a new photo is added to the gallery, I want to save that change to the database.

Solution: Here’s the jQuery code that I used to make it happen.


<script>
  $(document).ready(function(){
    $("#photos li").draggable();
    $("#gallery").droppable({
      accept: '.ui-draggable',
      drop: function (event, ui) {
        var id = ui.draggable.attr('id').replace('photo_', '');
        $.post("saveToGallery.php", { photo_id: id });
      }
  });
</script>

<div id="gallery"></div>

<ul id="photos">
  <li id="photo_1">photo 1</li>
  <li id="photo_2">photo 2</li>
  <li id="photo_3">photo 3</li>
</ul>

Notice the bold line. This is the line I had trouble figuring out. When a photo is dropped into the gallery area, the ‘photo_’ part of the name is stripped from the li tag ID leaving the number or ID of the photo. The photo ID is then passed to saveToGallery.php. The saveToGallery.php script can then get $_POST[‘photo_id’] and save it to the gallery.

Let me know if you have questions or a better way to do this!

Leave a Comment

Your email address will not be published. Required fields are marked *