Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize data for AJAX using HTML5sortable

Tags:

jquery

sorting

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!

like image 768
jtheman Avatar asked Jan 14 '23 21:01

jtheman


1 Answers

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(",");

like image 64
Kevin B Avatar answered Jan 27 '23 16:01

Kevin B