Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joemottershaw's avatar

Laravel 5 AJAX Sort Order data (jQuery Sortable) with no HTML form

I'm to trying to store a sort order to each article within a help centre for my new site using Laravel 5 and having a bit of trouble getting it to work. I'm using jQuery UI's .sortable for arranging the elements on the page, and since there are going to be multiple sections throughout the site where areas are sortable, my jQuery script is built in a way for a 'one script for all' purposes. Hence the use of data-* attributes and route name references.

Here is the code I've got so far:

routes.php

Route::post('admin/help-centre/category/{category_id}/section/{section_id}/article/sort-order', 'AdminHelpCentreArticleController@sortOrder');

AdminHelpCentreArticleController.php

public function sortOrder($category_id, $section_id)
{
    /* Return ------------------------------------- */
        return [
            'category_id' => $category_id,
            'section_id' => $section_id
        ];
}

show.blade.php (Admin Article Listing)

<ul id="help-center-articles-sort" class="sortable">
    @foreach ($helpCentreArticles as $helpCentreArticle)
        <li class="sortable-element" data-sortable-element-id="{{ $helpCentreArticle->id }}">
            <a href="{{ action('AdminHelpCentreArticleController@show', array($helpCentreCategory->id, $helpCentreSection->id, $helpCentreArticle->id)) }}" target="_self">{{ $helpCentreArticle->title }}</a>
        </li>
    @endforeach
</ul>

<a href="{{ $helpCentreSection->id }}/article/sort-order" target="_self" class="button bm-remove w-full sortable-save" data-sortable-id="help-center-articles-sort">Save Order</a>

scripts.js (includes CSRF Token _token)

var csrfToken = $('meta[name="csrf-token"]').attr('content');

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (options.type.toLowerCase() === 'post')
    {
        options.data += options.data ? '&' : '';
        options.data += '_token=' + csrfToken;
    }
});

$(document).ready(function() {
    $('.sortable').sortable();

    $('.sortable-save').on('click', function(e) {
        e.preventDefault();

        var route = $(this).attr('href'),
            sortableID = $(this).attr('data-sortable-id');

        var data = $('#' + sortableID + ' .sortable-element').map(function() { 
            return $(this).attr('data-sortable-element-id');
        }).get();

        $.ajax({
            type: 'POST',
            url: route,
            dataType: 'json',
            data: { id_array: data },
            success: function(data) {
                console.log(data);
            }, error: function(data) {
                console.log(data);
            },
        });
    });
});

Everything so far is working in terms of the return response in the console, which is Object {category_id: "1", section_id: "1"}. But no matter what I try, I cannot seem to pass through the data map to the controller to use it.

I've tried a bunch of guesswork since I cannot find a single decent tutorial on AJAX in Laravel 5 anywhere, and I've tried things such as adding a $data parameter to the sortOrder() method, I've tried Input::all() and Request::all but it all returns errors (I'm guessing cause it's not an actual form?).

Once I've got the data to be passed through to the controller I'll be able to save the sort order to the database easily enough. But I can't quite get to that stage, any ideas?

I should probably note that I do have a HelpCentreArticle model and a HelpCentreArticleRequest request too, here's some of the code from each file in case they are also needed:

HelpCentreArticle.php

class HelpCentreArticle extends Model {
    protected $fillable = [
        'category_id',
        'section_id',
        'title',
        'content',
        'excerpt',
        'is_visible',
        'sort_order',
        'created_by',
        'updated_by',
    ];
}

HelpCentreArticleRequest.php

class HelpCentreArticleRequest extends Request {        

    /* Authorization ------------------------------ */
        public function authorize()
        {
            return true;
        }


    /* Validation rules --------------------------- */
        public function rules()
        {
            $rules = [
                'title' => 'required|min:3',
                'content' => 'required|min:10',
            ];

            return $rules;
        }

}

I wasn't sure if I needed to add HelpCentreSectionRequest $request as the last parameter of the sortOrder() method, so I could use $request->all() but it just returns a 422 (Unprocessable Entity) in the console log.

0 likes
6 replies
unitedworx's avatar

@JoeMottershaw try console.log(route); and see if you are calling the correct route not only console.log(data); to see if you are passing the correct data!

P.S. a good idea is to use debugbar as well since it will help you see the response of your ajax calls and see what error exactly you are getting ( you get a drop down on the right side of the debug bar with all you ajax calls so you can switch to seem and see their response ) rhttps://github.com/barryvdh/laravel-debugbar

JarekTkaczyk's avatar

@JoeMottershaw AJAX has pretty much nothing to do with Laravel, or any other back-end framework for that matter.

If you send the correct request, then your server will respond accordingly.

If you are getting errors (would be worth showing them btw) then apparently the request is not what your controller expects.

joemottershaw's avatar

@JarekTkaczyk I understand Laravel is a backend framework but that's kind of what I'm asking, what request am I supposed to send. Trying to use Request or Input doesn't seem to work, I have got the AdminHelpCentreArticleController to work now (and it was nothing to do with my jQuery AJAX in my scripts.js file), but it's working in a way that I feel is not the 'Laravel way' so to speak.

This is my new Controller method that I'm using, and it uses $_POST which just doesn't seem right, but it updates accordingly and returns the success response:

public function sortOrder()
{

    /* Variables ---------------------------------- */
        $id_array = $_POST['id_array'];
        $sort_order = 1;


    /* Query Update ------------------------------- */
        foreach($id_array as $id) {
            $helpCentreArticle = HelpCentreArticle::where('id', $id)->first();

            $helpCentreArticle->sort_order = $sort_order;
            $helpCentreArticle->save();

            $sort_order++;
        }


    /* Return ------------------------------------- */
        return ['success' => true];
            
}

Like I said, I just don't think using $_POST is the correct approach, it seems untidy...

JarekTkaczyk's avatar

@JoeMottershaw OK, but what was the error you got? $_POST['id_array'] would be Input::get('id_array') the laravel way, that's all.

unitedworx's avatar
Level 8

If Input::get('id_array'); does not work then make sure to add "Use Input;" at the top of your controller!

joemottershaw's avatar

@JarekTkaczyk Thank you for confirming that Input::get() was the correct way and I wasn't going mad, I had tried that like I said, but I was missing the use Input; at the top of my controller as I thought it was already accessible, but I was wrong. This is now working as expected, I appreciate the help!

Please or to participate in this conversation.