0

I'm building a blog in Laravel v5.2 just to learn the system. I wanted to use jQuery UI Sortable. However whenever I try and sort the list it returns "POST http://localhost:3000/posts/reposition 500 (Internal Server Error)" in Chrome's console.

I took a look at jQuery UI Sortable, then write order into a database however I still cannot get it to work.

I'm looking to either see why I'm getting (Internal Server Error). I'm new to Laravel and not sure if my update method is wrong or if I'm just totally doing it wrong.

Thanks in advance!

Here is my code:

Controller:

    public function sort($cat_id)
    {
        $posts = DB::table('posts')->where('category_id', '=', $cat_id)->orderBy('position', 'ASC')->get();

        return view('posts.sort')->with('posts', $posts)->with('cat_id', $cat_id);
    }


    public function reposition()
    {
        $i = 0;

        foreach ($_POST['item'] as $value) {
            // Execute statement:
            // UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
            $i++;
            DB::table('posts')->where('id', '=', $value)->update([ 'position' => $i ]);
        }
    }

View:

        <ul class='sort-post-list' style="list-style:none;">
            @foreach($posts as $post)
                <li id="item-{{ $post->id }}">{{ $post->title }}</li>
            @endforeach
        </ul>

        <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
            $('.sort-post-list').sortable({
                axis: 'y',
                update: function (event, ui) {
                    var data = $(this).sortable('serialize');

                    // POST to server using $.post or $.ajax
                    $.ajax({
                        data: data,
                        type: 'POST',
                        url: '{{ route('posts.reposition') }}'
                    });
                }
            });
        </script>

Outputted HTML:

<ul class='sort-post-list' style="list-style:none;">
    <li id="item-1">Introduction and Approach to Materials</li>
    <li id="item-2">Teaching Philosophy</li>
    <li id="item-3">Acknowledgements</li>
</ul>

<script>
    $('.sort-post-list').sortable({
        axis: 'y',
        update: function (event, ui) {
            var data = $(this).sortable('serialize');

            // POST to server using $.post or $.ajax
            $.ajax({
                data: data,
                type: 'POST',
                url: '//localhost:3000/posts/reposition'
            });
        }
    });
</script>

Routes:

Route::get('posts/sort/{cat_id}', [ 'uses' => 'PostController@sort', 'as' => 'posts.sort' ]);
Route::post('posts/reposition', [ 'uses' => 'PostController@reposition', 'as' => 'posts.reposition' ]);
Community
  • 1
  • 1
Brandy
  • 544
  • 2
  • 11
  • 30
  • @Volatil3 Do i need a CsrfToken for this request? If so, where do I actually put the token? `[2016-12-08 11:52:02] local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\project\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:67` – Brandy Dec 08 '16 at 16:54
  • Check this out: https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token – Volatil3 Dec 08 '16 at 16:58
  • You can also pass a hidden form field by using `{{ csrf_field() }}` in your form which generates a form field with name `_token`, you then access the value and send a form field via Ajax with name `_token` – Volatil3 Dec 08 '16 at 17:00
  • @Volatil3 After some googling I found a solution! Thanks for the help and pointing me in the right direction! – Brandy Dec 08 '16 at 17:10
  • Glad to know :) – Volatil3 Dec 08 '16 at 17:26

1 Answers1

0

So with @Volatil3's help and some random googling, I finally got it to work.

<script>
    var getXsrfToken = function () {
        var cookies = document.cookie.split(';');
        var token = '';

        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].split('=');
            if (cookie[0] == 'XSRF-TOKEN') {
                token = decodeURIComponent(cookie[1]);
            }
        }

        return token;
    };
    $.ajaxSetup({
        headers: {
            'X-XSRF-TOKEN': getXsrfToken()
        }
    });
    $('.sort-post-list').sortable({
        axis: 'y',
        update: function (event, ui) {
            var data = $(this).sortable('serialize');

            // POST to server using $.post or $.ajax
            $.ajax({
                data: data,
                type: 'POST',
                url: '{{ route('posts.reposition') }}'
            });
        }
    });
</script>
Brandy
  • 544
  • 2
  • 11
  • 30