I am using jQuery UI sortable plugin to manage the weight values of my data in my database. Out of the box, the jQuery sortable serialization will return all of the data indexes in the list to be updated. This is unnecessary for me since the only items that have a weight change on update are those between the the new index of the item and the previous index (or vice versa).
For example, lets look at the following dataset:
<div id="sortable">
<div id="data_A">Data A</div>
<div id="data_B">Data B</div>
<div id="data_C">Data C</div>
<div id="data_D">Data D</div>
<div id="data_E">Data E</div>
<div id="data_F">Data F</div>
</div>
[0] = A
[1] = B
[2] = C
[3] = D
[4] = E
[5] = F
If I move D to position 1 in the list, we now have the following:
<div id="sortable">
<div id="data_A">Data A</div>
<div id="data_D">Data D</div>
<div id="data_B">Data B</div>
<div id="data_C">Data C</div>
<div id="data_E">Data E</div>
<div id="data_F">Data F</div>
</div>
[0] = A
[1] = D
[2] = B
[3] = C
[4] = E
[5] = F
Only indexes 1 (new position) through 3 (previous position) are effected and require database updates to their weights.
My question is, how would I only serialize this particular dataset each time on an update?
Here is where I am at currently with my code:
$("#sortable").sortable({
placeholder: "sortable-placeholder",
start: function (event, ui) {
$(this).attr('data-previndex', ui.item.index());
},
update: function (event, ui) {
var newPosition = ui.item.index();
var prevPosition = $(this).attr('data-previndex');
$.ajax({
type: "POST",
url: "/topics/updateorder",
// sends all data ** TODO: WE ONLY WANT TO PASS SERIALIZED DATA FOR INDEXES newPosition - prevPosition (or visa-versa) **
data: $(this).sortable("serialize") // currently sends data[]=A&data[]=D&data[]=B&data[]=C&data[]=E&data[]=F, we want data[]=D&data[]=B&data[]=C
});
}
});
Obviously I need a custom serializer or some sort (I think?), just not sure how. One issue with only passing the changed data, however, is that I can no longer update weight’s based off of the indexes of the posted form data (since all of it is no longer passed). I will have to pass their index values relative to all the other data along with it somehow as well.
Thanks.
I would think an easier way of doing this would be to simply pass the new position of the element to the server. That way you’re not sending data for all the elements (which sounds like what you’re looking to avoid).
Take a peek at the events for the sortable widget: http://jqueryui.com/demos/sortable/#events
You could bind a function to update which could be used to get the new position of the element and send it to the server via ajax.
Since the server knows the element and the old position of it, the server can handle the calculations needed to “push” all the remaining elements down one position, and you’re only sending a string and integer to the server in your request.