Hi I am trying to use jquery sortable and laravel to order some tasks in my database however when I try to serialise the data it seems like it is lost, as when I console log the variable I assign it to it is blank.
e.g.
var data = $(this).sortable('serialize');
console.log(data);
I have also tried the following and it comes back undefined in the console
var id = $(this).attr("data-task-id");
console.log(id);
My full jQuery is as follows:
$('.sortable').sortable({
cursor: 'move',
axis: 'y',
update: function (event, ui) {
var id = $(this).attr("data-task-id");
console.log(id);
var data = $(this).sortable('serialize');
console.log(data);
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/backlog/sort/update'
})
}
});
and my controller is as follows:
public function updateBacklogOrder() {
$updateRecordsArray = Input::all();
$i = 1;
// Loop though the <li>
foreach ($updateRecordsArray as $recordID) {
BacklogTask::where('id', $id)->update(array('order' => Input::get('order')));
$i++;
}
return Response::json('ok');
}
My blade file is as follows:
@foreach($tasks as $task) id}}">{{$task->name}} @endforeach
This renders the following:
Task One Task Two Task Three Task FourIts strange that the data is not being serialized using the sortable method, if I move it outside it complains that I've loaded this outside of the sortable method. Any ideas what I am doing wrong??
You need
id
attributes to useserialize
. If you have onlydata
attributes it won't work. Structure should be like this:That'll output a string like this:
You can customize a bit more by setting your wanted key, like this:
This will output:
But you need
id
attribute, and it must be properly formatted (default is underscore between key and value, but you can use "=" and "-" also. In your case, you can add ids dynamically on update, but it would be more efficient setting them in theHTML
directly. But this should give an output:EDIT:
The order of the parameters will be in the order they are in the sortable. Like this:
SECOND EDIT:
Turns out there's a way to use other attributes in serialize, but you need to set different options. This should work without assigning an id:
To clarify a bit further, if you take both parts, you'll see you can get
post
pretty much the string you want according to your needs. At this point, from what I understand from your controller, maybe serialize isn't necessarily the best way to go, but since you already have your setup, you could send parameters in the formid=order
this way: