I have an sortable grid of elements, that updates its value to DB after user moves the element. The problem is, I don't know how to update the id of all previous elements to a new one without reloading the page.
In PHP, I would do something like this (code from FAQ of one of my older pages), but I can't use PHP (it has to happen without any page reloading, right after user places element he moved):
if ($old_order > $order){
$result = dbquery("UPDATE faq SET orders=orders+1 WHERE orders>='$order' AND orders<='$old_order'");
}else{
$result = dbquery("UPDATE faq SET orders=orders-1 WHERE orders>='$old_order' AND orders<='$order'");
}
I would like to do that with jQuery, basically I have 7 elements with id from 0 to 6 and every time user changes the position, I serialize it and send it with ajax to an php code that saves it.
What it does now:
- Move elemtent 1 to position 4.
- Saves and works.
- Move element 3 to position 2
- Moves element 1 from position 4 back to his old one, as the ID of it is still 1 and not 4.
What I want to do:
- Move element 1 to position 4
- Change ID of element 1 from 1 to 4
- Change ID of element 2, 3 and 4 by -1 to id 1, 2 and 3
I hope somebody understands me and can help me.
jQuery code I actauly use:
$(".content-page").sortable({
start: function(e,ui){
ui.placeholder.height($(".sorted-icons").outerHeight(true));
ui.placeholder.width($(".sorted-icons").outerWidth(true));
},
placeholder: 'placeholder',
items: '.sorted-icons:not(.new_icon)',
update: function(e,ui) {
var order = $(this).sortable("serialize") + '&order=icons' + '&content_id=' + $(this).attr("data-shortcut-id");
console.log(order);
$.post("page_ajax.php", order).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
});
}
}).disableSelection();
Html code basically looks like this with content inside of that div thats irelevant:
echo "<div class='sorted-icons' id='icon_$id'>";
If you have any questions, just comment and Ill try to answer them and update the queston.
Fixed jQuery:
var i = 0;
$(this).children('.sorted-icons').each(function(){
$(this).attr('id', 'icon_' + i);
i++;
});
Still have problem with PHP part tho. Its saving them in weird orders.