Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Sortable - saving order when button clicked

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>
like image 726
EmWe Avatar asked Jan 09 '23 23:01

EmWe


1 Answers

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);
    });
});
like image 114
K K Avatar answered Jan 14 '23 08:01

K K