Simple way to create Drag and Drop using jQuery, and save data using PHP cookie, simple drag and drop tutorial with full example code.

How To Create Drag And Drop

Using jQuery and jQuery UI, we will create Drag and Drop, after that we will use jQuery Ajax to set PHP Cookie.

Drag And Drop Demo

Check live demo.

Download Example

Download demo example from Our Server.

Create Drag And Drop

Include jQuery & jQuery UI before </head> tag:

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui-custom.min.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>

Now create new JavaScript file “ajax.js” and enter this code inside it:

// By Qassim Hassan, wp-time.com

$(function(){

    $('.drag').draggable( { helper:"clone", containment:"document" } ); // element you want to drag it

    $('.drop').droppable({ // place to drop element inside it

        drop:function(event, ui) { // if drag and drop, will be change element place and set php cookie

            ui.draggable.detach().appendTo($(this)); // change element place

            var inputValue = $(this).attr("id"); // get place ID value

            $(".cookie-value").val(inputValue); // set place ID value to input

            var getInputValue = $(".cookie-value").val(); // get cookie value

            $.ajax({

                type: "POST",

                url: "set_cookie.php?place="+getInputValue, // send php cookie value to server

                cache: false,

                success: function(displayevent) {
                    $("body").append(displayevent); // set php cookie to index page
                }

            });

        }

    });

});

Now add this code before </head> tag, this code to check if has PHP cookie or not:

<!-- if has php cookie -->
<?php if ( isset($_COOKIE['place']) ) : ?>
    <script type="text/javascript">
        $(function(){
            var getCookieValue = "#<?php echo $_COOKIE['place']; ?>"; // get cookie value
            $(".drag").appendTo(getCookieValue); // change element place
        });
    </script>
<?php endif; ?>

Now if has PHP cookie, element “.drag” will be append to “.drop” element, enter this HTML code:

<p class="drag" style="color:#fff;background:rgba(0,0,0,0.5);">Drag and Drop me</p><!-- element you want to drag it -->

<div id="green" class="drop" style="background:green; display:block; width:100%; padding:30px;box-sizing:border-box;"></div><!-- place to drop element inside it -->

<input class="cookie-value" type="hidden" value=""><!-- php cookie value will be in this input -->

Finally, create new PHP file “set_cookie.php” and enter this code inside it:

<?php

    if( isset($_GET["place"]) ){
        setcookie("place", $_GET["place"], time() + 60); // 60 = 1 minute, cookie will be removed after 1 minute
    }

?>

Download the previous example.