Rainn's avatar
Level 1

How can I change the order ID of my categories using SortableJS for jQuery, and AJAX?

I am trying to use this JavaScript library called SortableJS along with jQuery & jQuery SortableJS. I have the front-end functionality working, but my issue is trying to get it to work successfully with an AJAX request.

JavaScript

<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-sortablejs@latest/jquery-sortable.js"></script>
<script>
$(document).ready(function(){
    $("#sortable-cards").sortable({
        animation: 350,
        easing: "cubic-bezier(1, 0, 0, 1)",
        stop: function() {
            $.map($(this).find('.col-lg-4'), function(el) {
                var id = el.id;
                var order = $(el).index();
                $.ajax({
                    url: '{{route('manage.orderCategories')}}',
                    type: 'POST',
                    data: {
                        id: id,
                        order: order
                    },
                });
            });
        }
    });
});
<script>

Sortable Cards Div in my Blade File

<div id="sortable-cards" class="row justify-content-center">
    @foreach($categories as $category)
    <div id="{{$category->order}}" class="col-lg-4 col-12 mt-4">
        <div class="card shadow">
            <div class="card-body">
                <h3>{{$category->name}}
                <p class="text-muted">{{$category->description}}<p>
                ID: {{$category->id}}<br>
                Order: {{$category->order}}<br>
            </div>
        </div>
    </div>
    @endforeach
</div>

Routes

Route::post('categories/orderCategories', 'Manage\ManageCategoriesController@orderCategories')->name('orderCategories');

Controller

public function orderCategories()
{
    $categories = Category::orderBy('order', 'ASC')->get();
    $id = Input::get('id');
    $order = Input::get('order');
    foreach ($categories as $item) {
        return Category::where('id', '=', $id)->update(array('order' => $order));
    }
}

The expected result is that when a sortable card is moved it will send an AJAX request to the controller and update the 'order' column in the database. Like I mentioned before the front-end functionality works fine, and there were no error messages present. If you need more information please let me know. Thank you for your help

0 likes
0 replies

Please or to participate in this conversation.