1

I know this question has been asked before but the solutions did not work for me. I am trying to save the new ordering of items to the database.

I have simplified it very considerably but this is the basic idea of it. I have a form with a sortable list embedded in it.

<form id="itemlist">
    <ul id="itemsort">
       <li id="Item_1">Item<input type="hidden" name="itemid[]" value="itemsRowID01"/></li>
       <li id="Item_2">Item<input type="hidden" name="itemid[]" value="itemsRowID02"/></li>
       <li id="Item_3">Item<input type="hidden" name="itemid[]" value="itemsRowID03"/></li>
       <li id="Item_4">Item<input type="hidden" name="itemid[]" value="itemsRowID04"/></li>
    </ul>
</form>

I have JQuery and JQuery UI Loaded and the The Following code enables the sortable list function and posts the item ids and New sort order to a php script. the "editor" variable is a public variable that is set on load it works fine. The sorting works fine but the neworder value that posts doesn't seem to change when I re-order the list.

//sorting feature  
    $("#itemsort").live('hover', function() {
        $("#itemsort").sortable({ 
            opacity:.5,
            update : function () {          

                var neworder =  $('#itemsort').sortable('serialize');
                var inputs = serializePost('#itemlist');

                $.post("core/actions.php",{
                   'order': editor,
                   'inputs': inputs,
                   'neworder': neworder},function(){

                       alert("Order saved.", 1);

                });
            } 
        });
    });

On actions.php...

    if(isset($_POST['order'])){

            //set a variable for each post
            $batchid = $_POST['inputs']['itemid'];

            parse_str($_POST['neworder'], $neworder);

            //count the number of entries to be ordered
            $count = count($batchid);        

            //use the count to create an incremental loop for each item to be updated.
            $i=0;
            while ($i <= $count) {

   $query ="UPDATE {$_POST['order']} SET order=$neworder[item][$i] WHERE id=$batchid[$i]";
                ++$i;
            }
        }

I'm not sure why the order I get for each item will not change.

Any Ideas?

-L

2
  • 6
    Holy SQL Injection Vulnerability, Batman! $query ="UPDATE {$_POST['order']} SET order=$neworder[item][$i] WHERE id=$batchid[$i]"; Your original question aside, this code is extremely dangerous. You need to make sure you're sanitizing your input variables before you pass them to a query, otherwise you might just find yourself in a world of hurt when someone ill-intentioned sets $_POST['inputs']['itemid'] to 10 OR 1=1 or similar. Commented Sep 8, 2011 at 3:32
  • 5
    Yeah i know sorry, That's just the simplest example of what I'm trying to do. I actually use classes and abstraction layers to protect my methods from injection. I didn't want to try and explain all the classes and parent classes etc. Hopefully it still makes enough sense to debug the logic in my actions.php script. Commented Sep 8, 2011 at 6:31

2 Answers 2

11
$("#list").live('hover', function() {
        $("#list").sortable({

            update : function () {

                var neworder = new Array();

                $('#list li').each(function() {    

                    //get the id
                    var id  = $(this).attr("id");
                    //create an object
                    var obj = {};
                    //insert the id into the object
                    obj[] = id;
                    //push the object into the array
                    neworder.push(obj);

                });

                $.post("pagewhereyouuselist.php",{'neworder': neworder},function(data){});

            }
        });
    });

Then in your PHP file, or in this example "pagewhereyouuselist.php"

$neworderarray = $_POST['neworder'];
//loop through the list of ids and update your db
foreach($neworderarray as $order=>$id){    
    //you prob jave a connection already i just added this as an example
    $con = mysql_connect("host","username","password");

    if (!$con){
         die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("my_db", $con);

    mysql_query("UPDATE table SET order = {$order} WHERE id = {$id}");
    mysql_close($con);

}

that should do it i didn't test it as it is an example connection. the actual script I am actually using is more specific to my program this is a simplified version to show the concept

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

Comments

7

Try this:

Your HTML fields

<form id="itemlist" method="POST">
    <ul id="itemsort">
        <li id="Item_1">Item 1<input type="hidden" name="itemid[]" value="itemsRowID01"/></li>
        <li id="Item_2">Item 2<input type="hidden" name="itemid[]" value="itemsRowID02"/></li>
        <li id="Item_3">Item 3<input type="hidden" name="itemid[]" value="itemsRowID03"/></li>
        <li id="Item_4">Item 4<input type="hidden" name="itemid[]" value="itemsRowID04"/></li>
    </ul>
</form>

JS to send order:

$("#itemsort").live( 'hover', function() {
    $("#itemsort").sortable({
        update: function () {          
            var inputs = $('#itemlist').serialize();
            $.post("./jq-ui-test.php", inputs, alert("Order saved.") );
        } 
    });
});

Saving order:

if( isset( $_POST['itemid'] ) && is_array( $_POST['itemid'] ) ) {
    foreach( $_POST['itemid'] as $order => $item ) {
        $order = intval( $order );
        $item_esc = mysql_real_escape_string( $item );
        $sql_query = "UPDATE {$_POST['order']} SET order={$order} WHERE id = '{$item_esc}'";
    }
}

Also, if you want that start order start from 1 ( not from 0 ) change $order = intval( $order ); to $order = intval( $order ) + 1;

3 Comments

So is this just trying to use the items position in the itemid array of row ids so set its position in the DB? I can't seem to get it to work. When your serialize the itemlist does it use the original HTML layout or the new adjusted one via the javascript?
It seems to use the order of the original HTML and not the order of the sorted...maybe serializing the sorted items like before instead?
I still Can't get it to work. The order of the serialized form ids does not reflect the order change by drag and drop. I'm pulling my hair out now....

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.