passing input name with ajax

Viewed 1061

I have this script that store item position in my database

    var set = $('#set');
    var set_x = set.offset().left;
    var set_y = set.offset().top;   
    var id = <?php echo $id ?>;

  $( "#set div" ).draggable({ 
    stack: "#set div",
      stop: function(event, ui) {
          var pos_x = ui.offset.left - set_x;
          var pos_y = ui.offset.top - set_y;
          var need = ui.helper.data("need");

          console.log(pos_x);
          console.log(pos_y);
          console.log(need);

          //Do the ajax call to the server
          $.ajax({
              type: "POST",
              url: "posinsert.php",   
              data: { x: pos_x, y: pos_y, need_id: need ,id:id,item1:item}
            }).done(function( msg ) {
              alert( "Data Saved: " + msg );
            }); 
      }
  });

});

This is my HTML

<div id="set">
  <div id="draggable" data-need="1">
    <p><img style="width:30%" src="./img/floor_plan_images/camera_top.png"</p>
    <input type="hidden" name="item1">
</div>

      <div id="draggable" data-need="2">
    <p><img style="width:30%" src="./img/floor_plan_images/camera_top.png"</p>
    <input type="hidden" name="item">
</div>
</div>
<div class="floor" id="droppable" ></div>

How can I pass the input name to my database using AJAX?

My item position is stored but in need the item name also.

And how can I update the position after moving the same item?

2 Answers

Since the input has a name it gets posted, but it's missing the value attribute. I may be wrong, but I think it's because your hidden input fields are missing the value attribute. The input tag should be like:

<input type="hidden" name="item" value="yourValue" />

Use var name = $(ui.helper[0]).find('input').attr('name'); to get the name like below.

var set = $('#set');
    var set_x = set.offset().left;
    var set_y = set.offset().top;   
    var id = 10;


  $( "#set div" ).draggable({ 
    stack: "#set div",
    stop: function(event, ui) {
          var pos_x = ui.offset.left - set_x;
          var pos_y = ui.offset.top - set_y;
          var need = ui.helper.data("need");
          // Get name of the input element
          var name = $(ui.helper[0]).find('input').attr('name');

          console.log(pos_x);
          console.log(pos_y);
          console.log(need);
          console.log(name);

        }
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  
  
<div id="set">
  <div id="draggable" data-need="1">
    <p>
    <img style="width:30%" src="./img/floor_plan_images/camera_top.png">
    </p>
    <input type="hidden" name="item1"/>
</div>

     <div id="draggable" data-need="2">
    <p><img style="width:30%" src="./img/floor_plan_images/camera_top.png">
    </p>
    <input type="hidden" name="item">
</div>
</div>
<div class="floor" id="droppable" ></div>

Related