levi lucas
levi lucas

Reputation: 99

Ajax returning 500 error in laravel 5.2

Laravel 5.2 - new application

Ive only just got back into laravel, and im having trouble with an ajax post.

Basically when you reorder the list its calling ajax to change the order and save it in the database. ive been researching around but none seem to be helping me..

What i have so far....

html/blade.php code:

<ul class="sortable">
    @foreach ($pages as $page)
        <li class="ui-state-default" data-id="{{ $page->id }}">{{ $page->name }}</li>
    @endforeach
</ul>

Ajax

$(function() {
    $('.sortable').sortable().bind('sortupdate', function(e, ui) {

        var id = $('ul.sortable li').map(function(){
            return $(this).data("id");
        }).get();

            $.ajax({
                method: 'post',
                url: '/abc',
                data: {
                    id: id, 
                    _token: token
                },
                dataType: 'json',
                error: function (data) {
                    console.log('Error:', data);
                },
                success: function (msg) {
                    alert(msg);
                }
            });


        });
    });

Routes.php

Route::post('abc', 'HomeController@SomeFunction');

Controller

public function SomeFunction(Request $request){


    $id = $request->input('id');

    $i = 1;

    foreach($id as $val) {

        $page = Page::where('id', (int)$val)->first();

        $page->order = $i;
        $page->save();

        $i++;

    }


}

UPDATE:

Thank you for all the support from everyone above i have put all the suggestions that people helped me code better and solve the issue... I also found out that when i convert the $val to an int it was updating in the database. thank you

Upvotes: 0

Views: 153

Answers (2)

Abiodun
Abiodun

Reputation: 467

You forgot your request in the controller Make sure you are using

use Request And then edit your controller code to this format

public function SomeFunction(Request $request){


    $id = $request->input('id');

    $i = 1;

    foreach($id as $val) {

        $page = Page::where('id', $val)->first();

        $page->order = $i;
        $page->save();

        $i++;

    }


}

Upvotes: 0

Martin
Martin

Reputation: 1279

If you want to use jquery ajax in laravel you need to pass the laravel token in ajax request data!

 data: {
           id: 'id', _token: token
 },

Two quick tips you don't need to use the meta tags in html and any ajax setup. The only thing that you need to do is that make a variable in your view named for example token var token = '{{Session::token()}}' and then pass it in ajax data. Other tip is that instead of using the static url, you can make a variable in your view to your post route var url = '{{Route("name")}}'.

Upvotes: 1

Related Questions