I am trying to use jQuery draggable/droppable to drag a list item to a div, upon which the list item will be deleted from the draggable ul and an ajax call will be made to delete the corresponding item in a MySQL database.
The HTML:
<ul id="draggable">
<li id="list_1">List item 1</li> // Incrementing ID nos. from database
<li id="list_2">List item 2</li>
<li id="list_3">List item 3</li>
</ul>
<div id="droppable"></div>
The jQuery so far:
$('#draggable li').draggable({
drag: function(event, ui) {
var id = $(this).attr('id').split("_");
id = id[1]; // OK so far - but how to pass this to droppable?
}
});
$('#droppable').droppable({
drop: function(event, ui) {
// How to get the id from draggable here so the correct list item is acted on?
$('#draggable li').remove();
$.ajax({
url: "delete.php",
type: "GET",
data: {
'id': id,
'user_id': user_id // user_id comes from PHP
}, // end ajax }
});
UPDATE
Many thanks for the responses. I got it to work using:
<script>
var user_id = "<?php print($user_id); ?>";
$(document).ready(function() {
$('#draggable li').draggable({
helper: 'clone'
});
$('#droppable').droppable({
accept: '#draggable li',
drop: function(ev, ui) {
var id = $(ui.draggable).attr('id').split("_");
var movie_id = id[1];
$('#draggable li#list_' + id).remove();
$.ajax({ // begin add ajax
url: "delete.php",
type: "GET",
data: { // begin add data
'id': id,
'user_id': user_id
} // end data
}); // end ajax
} // end drop function
}); // end droppable
}); // end ready
</script>
It seeems OK to me - are there any problems with that which you can see?
You can access the dragged element using using ui.draggable.attr('id')
inside your drop function.
Fiddle
See Documentation
You should not manage anything in your "drag" callback for many reasons:
Watch the updated JSFiddle: http://jsfiddle.net/nVx7a/23/
HTML:
<ul id="draggable">
<li id="list_1" data-id='1'>List item 1</li>
<li id="list_2" data-id='2'>List item 2</li>
<li id="list_3" data-id='3'>List item 3</li>
</ul>
<div id="droppable"></div>
And JS:
$(document).ready(function () {
$('#draggable li').draggable();
$('#droppable').droppable({
drop: function(event, ui) {
var $element = $(event.toElement), // equivalent to $(ui.helper);
id = $element.data('id'), // HTML5 way, equivalent to $element.attr('data-id');
// id = $(this).attr('id').split("_"); // HTML4 way
$YOUR_PHP_VAR = 1;
console.log($element, id, $YOUR_PHP_VAR);
// Lock the UI, display a loader or something...
$.ajax({
url: "delete.php",
type: "GET",
data: {
'id': id,
'user_id': $YOUR_PHP_VAR // user_id comes from PHP
}
}).done(function (response) {
console.log('success', response);
// Once your Database request is successfully executed, remove the element from your UI.
$element.remove();
}).fail(function (response) {
console.log('fail', response);
});
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With