evilscary
evilscary

Reputation: 2217

Store li order in Mysql DB with Jquery sortable

I have a sortable list in my site which saves the order of the list items with an ajax request to a php page. The problem is when the id of the LI (which is generated by the database) gets above 999 or so it begins to error as the array I'm sending to the PHP page becomes too long.

Is there a better way of doing this?

Currently my Jquery/ ajax is:

$(function() {
$('#sortable').sortable({
    update: function(event, ui) {
        var order = []; 

        $('#sortable li').each( function(e) {
            order[ $(this).attr('id') ] =  $(this).index() + 1;
        });

        var request = $.ajax({
            url: "ajax/save_order.php",
            type: "POST",
            data: {positions : order},
            dataType: "json"
        });
    }
});
});

My PHP page is:

$positions = $_POST['positions'];

foreach ($positions as $id_section => $order)
{
    $sql = sprintf("
        UPDATE      section_order
        SET     id_order = %d
        WHERE       id_section = %d
    ",
        $order,
        $id_section
    );
    $result = mysql_query($sql);
}

I've been trying to work out how to get the data from the sortable into a multidimensional array in jquery, but currently am drawing a blank.

Upvotes: 0

Views: 3475

Answers (1)

superphonic
superphonic

Reputation: 8074

OK I see. Seems a bit unwieldy for a user to manually drag and drop items in a list of over 1000 items. But I don't know how/why you are doing this so will assume it works for your application.

The below solution is actually from this SO question jQuery UI Sortable, then write order into a database

jQuery Sortable has a serialize function that takes care getting the order for you. Use it like below:

$('#sortable').sortable({
    axis: 'y',
    stop: function (event, ui) {
        var data = $(this).sortable('serialize');

        // POST to server using $.post or $.ajax
        $.ajax({
            data: data,
            type: 'POST',
            url: 'save_order.php'
        });
    }
});

And in the save_order.php file, just check what the posted data looks like and loop though it, should be able to do something like:

<?php
    foreach ($_POST['each_item_whatever...'] as $value) {

        // Database stuff

    }
?>

Upvotes: 1

Related Questions