javascript - Send multiple field arrays via ajax to Laravel 5
I need help with saving a drag n drop menu order. I use http://farhadi.ir/projects/html5sortable to drag and update the list. Each menu item has two hidden fields:id
andorder
. The order is updated dynamically when dropped. I don't know how to turn the fieldsid
andorder
into a correct array so I can update via AJAX into Laravel.
HTML - Menu :
<div>
<input name="menu[1][id]" type="hidden" value="1">
<input name="menu[1][order]" type="hidden" value="3">
</div>
<div>
<input name="menu[2][id]" type="hidden" value="2">
<input name="menu[2][order]" type="hidden" value="4">
</div>
<div>
<input name="menu[3][id]" type="hidden" value="3">
<input name="menu[3][order]" type="hidden" value="5">
</div>
jQuery - Drag/drop, update order value then send via ajax :
// Sortable options
$('.nav-pages__items').sortable({
handle: '.nav-pages__drag',
items: ':not(.home)'
}).bind('sortupdate', function() {
// When dropped clear list order
$(this).find('input[name=menu]').attr('value', '');
// Then update list order
$('.nav-pages__items li:not(.home)').each(function(i, element) {
element = i+1;
$(this).find('input.new-order').attr('value'),
$(this).find('input.new-order').attr('value', + element);
});
// !! Somehow create array to send/save !!
// Ajax to send
$.post('/menu-update', {
_token: token,
id: id,
order: order
}, function(data) {
if (data.status == 'success') {
console.log('success: ', data);
} else if (data.error == 'error') {
console.log('error: ', data);
};
});
});
PHP/Laravel - Not got this far (without errors):
public function update()
{
$menu = Input::all();
$save = Page::where('id', $menu['id'])->update([
'order' => $menu['order']
]);
if ($save) {
$response = [
'status' => 'success',
'msg' => 'Message here',
'id' => $menu['id'],
'order' => $menu['order'],
];
};
return Response::json($response);
}
To summarise:
- Get the
id
andorder
for each field group - Loop though them in js and crate correct array
- Send array to Laravel and update
order
based onid
Also, if there's a much simpler way to do this, I'm all ears.
Answer
Solution:
I don't believe you need those hidden inputs -- what about something like:
jQuery:
PHP/Laravel: