How can I get the X,Y co-ords of a JQueryUI draggable object, when it is dropped, and post them to something (a java servlet) using AJAX?

Im trying to store the location of it in a database, ive got the handler to do that done, Im a backend guy, but I suck with JavaScript!

Dani AI

Generated

As wants to persist a jQuery UI draggable's position to a servlet, use jQuery UI's own callbacks rather than raw mouse events. is right that the event object contains coordinates, but jQuery UI passes a convenient ui object to the stop callback that already accounts for the draggable's layout and offset parent. That makes the values easier to persist reliably.

Example (get coordinates on drop and POST JSON to a servlet):

$('.draggable').draggable({
  stop: function(event, ui) {
    var payload = {
      id: $(this).attr('id') || $(this).data('id'),
      x: Math.round(ui.position.left),
      y: Math.round(ui.position.top)
    };

    $.ajax({
      url: '/your/servlet/url',
      method: 'POST',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(payload),
      dataType: 'json'
    }).done(function(res){
      // success handling
    }).fail(function(xhr){
      // error handling
    });
  }
});

Notes and pitfalls to watch for:

  • ui.position is the element's current CSS top/left relative to its offset parent. ui.offset is document-relative. Pick the one that matches how you want to store/replay positions.
  • Ensure the draggable has a meaningful positioning context (for example position: absolute inside a positioned container), otherwise saved coords may not behave later.
  • For responsive layouts, consider storing percentages (x/parentWidth*100) instead of raw pixels so items reflow correctly.
  • Server-side: validate and clamp coordinates, require authentication/CSRF tokens, and accept the expected content type (JSON or form-encoded). If the servlet is on another origin, configure CORS.

jQuery UI docs for the stop event and jQuery ajax reference are useful: draggable stop and $.ajax.

use javascript to grab the "ondrop" event; The "event object" keeps x,y coordinate values updated at all times, assign to variables like:

var x = ["event object"].clientX;
var y = ["event object"].clientY;

and use your ready handler to post them by referencing x,y variables.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.