4

I'm using a neat sort plugin for jQuery, HTML5 Sortable http://farhadi.ir/projects/html5sortable/ but haven't found an ideal way of serialize data to send as an AJAX POST request (to update DB).

HTML

<ul class="sortable">
    <li data-id="1">One</li>
    <li data-id="2">Two</li>
    <li data-id="3">Three</li>
    <li data-id="4">Four</li>
    <li data-id="5">Five</li>
</ul>

jQuery

$('ul.sortable').sortable().bind('sortupdate', function() 
{
   var data = ??;  // serialize all data-id's ... this is my problem

   $.post('/sortupdate.php',data,function(){ // PHP script sets new order in DB
       alert('updated');
   });
});

So what I want to happen is that when I drag an LI item to a new position then the sortupdate event should trigger the function and send the new order of data-id attribute values. My current idea is to loop through the LI's and add attribute values to an array. Is there any smarter way of doing this, or, what is the most efficient way of doing the loop? (I'm mostly a backend guy you know). Thanks!

1 Answer 1

9

Since the plugin doesn't come with a built-in serialize method, you have to do it manually.

var dataIDList = $('ul.sortable li').map(function(){ 
    return $(this).data("id");
}).get().join(",");

(which is essentially what you described at the end, it loops through and creates a list.)

Now you can post it as a list:

$.post(url,{ idlist: dataIDList }, completeandler);

You could also post it as an array, just remove .join(",");

Sign up to request clarification or add additional context in comments.

4 Comments

That looks great! However the jQuery data() is new to me, I thought I would be using 'return $(this).attr("data-id")' - is data() better?
It depends on the situation. .data tries to guess at what the intended type of the value should be, for example, 1 will be parsed as an integer, { foo: "bar" } will be parsed as an object, etc. In your case you don't really care if it's an int or a string, so use whichever one you prefer. .attr() should be quicker if performance becomes a problem.
Thanks for the explanation! I tested and you solved my issue! :)
Plus1 for the answer... however I prefer to use $(this).children().map() instead of specifying the element again... because it is possible more than one ul.sortable exist in the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.