I have a list with items that should be sorted by the user with jQuery UI Sortable. After the user has chosen his final order of the list he has to click a button "Ready". After the button is clicked, the order should be sent to saveoder.php using serialize and Ajax.
I tried to surround the ajax call with a click event but then there will be a couple of POST-requests done depending on the count of sortable actions of the user. I need only one ajax post request.
$(function() {
$( "#sortable" ).sortable({
update: function(event, ui) {
var order = $(this).sortable('serialize');
$(document).on("click", "button" , function() { //that doesn't work
$.ajax({
data: order,
type: 'POST',
url: 'saverank.php'
});
});
}
}).disableSelection();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<ul id="sortable">
<li id="id_1">Item 1</li>
<li id="id_2">Item 2</li>
<li id="id_3">Item 3</li>
</ul>
<button>Ready</button>
There is a builtin method for doing this. Refer serialize or toArray
Demo: http://jsfiddle.net/lotusgodkk/GCu2D/539/
JS:
$(function () {
$("#sortable").sortable({
update: function (event, ui) {
var order = $(this).sortable('serialize');
$(document).on("click", "button", function () { //that doesn't work
$.ajax({
data: order,
type: 'POST',
url: 'saverank.php'
});
});
}
}).disableSelection();
$('button').on('click', function () {
var r = $("#sortable").sortable("toArray");
var a = $("#sortable").sortable("serialize", {
attribute: "id"
});
console.log(r, a);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With