3

guys.

I'm trying develope a webpage which has draggable function. I found a jQuery theme exactly I wanted, and I'm using that code.

I didnt modify a lot, but just added code that loads database using ajax and mysql. After loading db, the draggable function doesnt work. I think it's about the order of running the function. so I used setTimeout on the function that has draggable function and it worked.

But the problem is that I have to load database every 5 seconds, so I cant keep using setTimeout for the draggable function everytime I load db.

Is there any solutions that I can fix this problem?

Here is the code that I use

main.php

$(document).ready(function database(){

  if(window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  } else{
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
      document.getElementById("gallery").innerHTML = xmlhttp.responseText;
    }
  };
  xmlhttp.open("GET","db.php",true);
  xmlhttp.send();

   init();
});
setTimeout(function (){

  var $gallery = $("#gallery");
  var $gallery2 = $("#gallery2");
  var $trash = $("#trash");
  var $trash2 = $("#trash2");
  $("li",$gallery).draggable({
    cancel: "a.ui-icon",revert:"invalid",containment:"document",helper:"clone",cursor:"move"
  });
  $("li",$gallery2).draggable({
    cancel: "a.ui-icon",revert:"invalid",containment:"document",helper:"clone",cursor:"move"
  });
  $trash.droppable({
    accept: "#gallery > li",
    classes: {
      "ui-droppable-active": "ui-state-highlight"
    },
    drop: function( event, ui ) {
      deleteImage( ui.draggable );
    }
  });
  $trash2.droppable({
    accept: "#gallery2 > li",
    classes: {
      "ui-droppable-active": "ui-state-highlight"
    },
    drop: function(event, ui){
      deleteImage2(ui.draggable);
    }
  });
  $gallery.droppable({
    accept: "#trash li",
    classes: {
      "ui-droppable-active":"custom-state-active"
    },
    drop: function(event, ui){
      recycleImage(ui.draggable);
    }
  });
  $gallery2.droppable({
    accept: "#trash2 li",
    classes: {
      "ui-droppable-active":"custom-state-active"
    },
    drop: function(event, ui){
      recycleImage2(ui.draggable);
    }
  });
  var recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off' title='Recycle this image' class='ui-icon ui-icon-refresh'>Recycle image</a>";
  function deleteImage( $item ) {
    $item.fadeOut(function() {
      var $list = $( "ul", $trash ).length ?
      $( "ul", $trash ) :
      $( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $trash );
      $item.find( "a.ui-icon-trash" ).remove();
      $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
        $item
        .animate({ width: "100px" })
        .find( "img" )
        .animate({ height: "150px" });
      });
    });
  }
  function deleteImage2( $item ) {
    $item.fadeOut(function() {
      var $list = $( "ul", $trash2 ).length ?
      $( "ul", $trash2 ) :
      $( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $trash2 );
      $item.find( "a.ui-icon-trash" ).remove();
      $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
        $item
        .animate({ width: "100px" })
        .find( "img" )
        .animate({ height: "150px" });
      });
    });
  }
  var trash_icon = "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a>";
  function recycleImage( $item ) {
    $item.fadeOut(function() {
      $item
      .find( "a.ui-icon-refresh" )
      .remove()
      .end()
      .css( "width", "96px")
      .append( trash_icon )
      .find( "img" )
      .css( "height", "72px" )
      .end()
      .appendTo( $gallery )
      .fadeIn();
    });
  }
  function recycleImage2( $item ) {
    $item.fadeOut(function() {
      $item
      .find( "a.ui-icon-refresh" )
      .remove()
      .end()
      .css( "width", "96px")
      .append( trash_icon )
      .find( "img" )
      .css( "height", "72px" )
      .end()
      .appendTo( $gallery2 )
      .fadeIn();
    });
  }
  function viewLargerImage( $link ) {
    var src = $link.attr( "href" ),
    title = $link.siblings( "img" ).attr( "alt" ),
    $modal = $( "img[src$='" + src + "']" );
    if ( $modal.length ) {
      $modal.dialog( "open" );
    } else {
      var img = $( "<img alt='" + title + "' width='384' height='288' style='display: none; padding: 8px;' />" )
      .attr( "src", src ).appendTo( "body" );
      setTimeout(function() {
        img.dialog({
          title: title,
          width: 400,
          modal: true
        });
      }, 1 );
    }
  }
  $( "ul.gallery > li" ).on( "click", function( event ) {
    var $item = $( this );
    var $target = $( event.target );
    if ( $target.is( "a.ui-icon-trash" ) ) {
      deleteImage( $item );
    } else if ( $target.is( "a.ui-icon-zoomin" ) ) {
      viewLargerImage( $target );
    } else if ( $target.is( "a.ui-icon-refresh" ) ) {
      recycleImage( $item );
    }
    return false;
  });
  $( "ul.gallery2 > li" ).on( "click", function( event ) {
    var $item = $( this );
    var $target = $( event.target );
    if ( $target.is( "a.ui-icon-trash" ) ) {
      deleteImage2( $item );
    } else if ( $target.is( "a.ui-icon-zoomin" ) ) {
      viewLargerImage( $target );
    } else if ( $target.is( "a.ui-icon-refresh" ) ) {
      recycleImage2( $item );
    }
    return false;
  });
}, 1000);

db.php

    <?php
$host = "localhost";    // 자신의 mysql
$DB_name = "master";    // 데이터베이스 이름
$user = "root";         // 기본 사용자.
$password = "0000";     // apm 기본 암호

$conn = mysqli_connect($host, $user, $password, $DB_name);

if(!$conn){
    echo "fail!\n";
    die('Could not connect: ' . mysqli_error($con));
}

//else
$sql = "select * from sensorlist";
$result = mysqli_query($conn,$sql);
$rowcnt = mysqli_num_rows($result);
$filed_name = array('S_Ultrasonic','S_IR','S_Humidity','S_Temperature','S_Heatindex','S_Light','S_Gas');    //센서 필드명 집합

if($rowcnt == 1){   //right (data가 1행만 들어있는 게 맞는 지 체크)
    while($row = mysqli_fetch_array($result)){
        for($i=0;$i<count($filed_name);$i++){
            if($row[$filed_name[$i]] != NULL){
                echo "<li class='ui-widget-content ui-corner-tr ui-draggable ui-draggable-handle'>";
                echo "<h5 class='ui-widget-header'>" . $filed_name[$i] . "</h5>";
                echo "<a href='images/high_tatras.jpg' title='View larger image' class='ui-icon ui-icon-zoomin'> View larger</a>";
                echo "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a></li>";
            }
        }
    }
    //echo "No sensor";
} else if($rowcnt == 0) {   //data가 하나도 없으면 없다고 출력
    //없다고 출력
    echo "No sensor";
} else {    //이도 저도 아니면 땡!
    //db 에러 출력
    echo "No sensor";
}
mysqli_close($conn);

?>
4

1 Answer 1

1

Delegate you event if you have dynamically added elements, reinitialize your draggable plugin after the ajax is complete (do all your logic in the if of the onreadystatechange event)

Sign up to request clarification or add additional context in comments.

2 Comments

Yea, I'm actually doing it using setTimeout, but I kinda wanna know other solution.... (if there is).
I have to refresh the db every 5 seconds, so....... I dont want to make delay every 5 seconds using setTimeout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.