Search code examples
phpjqueryajaxdraggable

Draggable divs not working if created by Ajax


I'm using jQuery and Ajax to load a bunch of divs into a scrollable div ("letterHolder"):

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>

<script type="text/javascript">
$.ajax({
  url: "myphpscript.php",
  dataType: "json",   
  success: function(result) {
    $(".letterHolder").html(result['letter_array']);
  }
});
</script>
</head>

<body>

<div class="letterHolder">
</div>

</body>
</html>

The PHP script retrieves a list of filenames from the database and loads them into letterHolder, so it ends up looking like this:

<div class="letterHolder">
  <div class="drag_letter">file1</div>
  <div class="drag_letter">file2</div>
  <div class="drag_letter">file3</div>
  etc.
</div>

Now, I want to make those filename divs draggable, but this is not working:

$(".drag_letter").draggable({
 cursor: 'move',
 revert: true,
 helper: 'clone'   
});

It doesn't work if I put the draggable code into the page header, nor does it work if I put the code at the end of the page.

This was working fine before I tried creating the divs using Ajax.


Solution

    1. Using jQuery or java script append() function for adding DOM into an element instead of html()
    2. add draggable after appending elements

    you should send file names Like file1... file2... as a Json array From server

    and rewrite this:

    <script type="text/javascript">
    $.ajax({
        url: "myphpscript.php",
        dataType: "json",
        success: function(result) {
            $.each(result,function(k,v){
                $(".letterHolder").append($('<div></div>').html(v).addClass('drag_letter').draggable({
                    cursor: 'move',
                    revert: true,
                    helper: 'clone'
                }));
            });
        }
    });
    </script>