jQuery Draggable Droppable Pass IDs to Ajax

1.2k views Asked by At

I am trying to use jquery draggable/droppable to allow me to drag an item to a location and have it pass the id of the item AND the id of the location via ajax to a php file.

In summary if I have 10 items and 2 drag locations, I am hoping that if I dragged an item it would return something like item7 and location2.

Hope this makes sense, this is what I have so far, pretty basic but this only returns the item value, obviously because I think the location variable is unavailable (which I tried to fix unsuccessfully).

<script>
  $(function() {
   var location;
$("#draggable" ).draggable({
     revert: "valid",
     drag: function (event, ui) {
         var location = $(this).attr("id");
     }
    });
$(".droppable" ).droppable({
    activeClass: "ui-state-hover",
    hoverClass: "ui-state-active",
    drop: function( event, ui ) {
    var item = $(this).attr("id");

        $( this )
            .addClass( "ui-state-highlight" )
            .find( "p" )
            alert(item + location);
    }
});

});

As reminder I would like to add ajax to this if possible once I can retrieve both values so I can work it in the database.

1

There are 1 answers

0
Joshua Olds On BEST ANSWER

I figured it out, haven't tested the ajax part of it but the main goal was to retrieve both variables which worked with this

<script>
$(".draggable" ).draggable({
     revert: "valid",
     drag: function (event, ui) {   
     }
}); 
$(".droppable").droppable({
    drop: function(e, ui) {
        // This gets the ID of the item you are dragging
        var item_id = $(ui.draggable).attr('id');
        var location = $(this).attr("id");
        $( this )
            .addClass( "ui-state-highlight" )
            .find( "p" )
            alert(item_id + location);
        // Ajax call
        $.ajax({
            type: "GET",
            timeout: 10000,
            url: "item_update.php?item_id="+item_id+"&location="+location,
        });
    }
});
</script>