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

Ghaleon's avatar

Using $Ajax with Laravel

Hi guys ! I created a nested list with data from database. Also I'm using JQuery/JQuery UI to create a Drag/Drop event on each element of the list. But I keep getting:

500 (Internal Server Error)

The main idea is: I have a bunch of professors and each professor may have 0 or N classes to teach, lets pretend that:

John | Math | Physics

Dwayne | English

Now, lets say I want Dwayne to teach Math instead of John. SO I'll drag the math from John list and drop it on Dwayne. In the moment I drop the new element, I want to fire an ajax function to update my database:

My Code so far:

Routes

Route::get('professor', [
    'uses' => 'ProfessorController@index'
    ]);

Route::post('professor', [
    'uses' => 'ProfessorController@postProfessorList'
    ]);

Controller

class ProfessorController extends Controller
{
    public function index()
    {
        return View::make('professor', [
            'professores' => Professor::all()
        ]);
    }

    public function postProfessorList()
    {
        Professor::submit(Input::post('disciplina'), input::post('professor'), input::post('old'));
    }
}

My View

@extends('app')

@section('assets')
    <script type="text/javascript" src="{{ URL::to('/js/jquery.mjs.nestedSortable.js') }}"></script>
@stop

@section('content') 
    <ol>
        @foreach($professores as $prof)
            <li data-id=" {{ $prof->id }}">
                {{ $prof->nome }}
                <ol class="list-disc">
                    @foreach($prof->disc as $disc)
                        <li data-id="{{ $disc->id }}">{{ $disc->nome }}</li>
                    @endforeach
                </ol>
            </li>
        @endforeach
    </ol>

    <script type="text/javascript">
        $(function(){
            var old_teacher;

            $('.list-disc').sortable({
                connectWith: '.list-disc',
                start: function (event, ui){
                    old_teacher = ui.item.parent().parent().attr('data-id');
                    dd($old_teacher)
                },
                stop: function (event, ui){
                    $.ajax({
                        type: "POST",
                        url: '{{ URL::to("/professor") }}',
                        data: {disc: ui.item.attr('data-id'), professor: ui.item.parent().parent().attr('data-id'), old: old_teacher},
                        success: function(data){
                            //console.log(data);

                        }
                    });
                }
            });
        })
    </script>

@stop
0 likes
32 replies
nfauchelle's avatar

Check your laravel log. 500 sounds like an error with your PHP.

Ghaleon's avatar

@zachleigh Actually I'm not 100% sure of what I'm doing here. I'm just reading something here and there and trying to make it work ;s I haven't touch in anything like this token you mentioned.

@nfauchelle Where is it ? I set debug to true on Config\App.

'debug' => env('APP_DEBUG', true),
Ghaleon's avatar

@zachleigh Well, I think I did it right but still dont work:
I placed this on my view:

{!! csrf_field() !!}

Then I got:

<input type="hidden" name="_token" value="KeyHere">
lancebutler2's avatar

Now you need to send that csrf token in your ajax request. @zachleigh is right, and in Laravel 5 the csrf middleware is used on all post routes by default.

You need to add that token value to your ajax post request data.

$(function(){
            var old_teacher;

            $('.list-disc').sortable({
                connectWith: '.list-disc',
                start: function (event, ui){
                    old_teacher = ui.item.parent().parent().attr('data-id');
                    dd($old_teacher)
                },
                stop: function (event, ui){
                    $.ajax({
                        type: "POST",
                        url: '{{ URL::to("/professor") }}',
                        data: {disc: ui.item.attr('data-id'), professor: ui.item.parent().parent().attr('data-id'), old: old_teacher, _token: $('input[name="_token"]').val()},
                        success: function(data){
                            //console.log(data);

                        }
                    });
                }
            });
        })
lancebutler2's avatar

I am curious to know if

old: old_teacher

will work. old_teacher is declared in the start function, will it be accessible in another (stop) function?

Ghaleon's avatar

@lancebutler2 @zachleigh Thanks guys ! But still don't work.

$.ajax({
    type: "POST",
    url: '{{ URL::to("/professor") }}',
    data: {disc: ui.item.attr('data-id'), professor: ui.item.parent().parent().attr('data-id'), old: old_teacher, _token: $('input[name="_token"]').val()},
    success: function(data){
        //console.log(data);
    },
    error: function(data){
        console.log(data);
    }
});

Laravel Log:

[2015-08-08 12:14:24] local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in >F:\PathToProjectsFolder\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53

Update 2: After I trie this way:

$.ajax({
    type: "POST",
    url: '{{ URL::to("/professor") }}',
    data: { disc: ui.item.attr('data-id'), professor: ui.item.parent().parent().attr('data-id'), old: old_teacher, _token: {{!! csrf_token() !!}}   },
    success: function(data){
        //console.log(data);
    },
    error: function(data){
        console.log(ui.item.parent().parent());
    }
});

I'm getting:

Uncaught ReferenceError: MyTokenValueHere is not defined

lancebutler2's avatar
  1. unescaped blade values are written with only 1 of the squiggly braces {!! csrf_token !!} or simply escaping it and using {{ csrf_token() }} will work just fine as it's a string with not html anyways.

  2. When you fix that syntax, and then look at the source code on your page, what's the value of the csrf_token? If it's not a jumbled up set of letters/numbers, you may still need to set your application key. Your application key can be found in the file Config/app.php with the 'key' index. If it's set to env('APP_KEY', 'YourKeyHere'), then it's first looking in your .env file for an APP_KEY entry, and defaulting to 'YourKeyHere' if it couldn't find it. If It can't find it, in the console you can run 'php artisan key:generate' to generate a new application key.

Ghaleon's avatar

@lancebutler2 Thanks for helping me here man.

  1. Already fixed thanks.

  2. Source code is just like you said. A 'jumbled up set of letters and numbers'.
    When checking Config/app.php I have exactly this:

'key' => env('APP_KEY', 'SomeRandomString'),

My App_Key on .env file is different from the key generated in source code. So I have to replace it or run generate artisan command?

Ghaleon's avatar

@Francismori7 Thanks for helping me !

Update: Message from Laravel log file:

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method Illuminate\Http\Request::post()' in F:\PathToProject\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:210 Stack trace: #0 {main}

Francismori7's avatar

You should have a stack trace of that error also, clear the logs and try again, then copy the whole errors.

Ghaleon's avatar

@Francismori7 Here it is: Cleaned the log, then when the the ajax tries to execute: That's all the errors.

[2015-08-08 14:38:54] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method Illuminate\Http\Request::post()' in F:\PathToProject\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:210 Stack trace: #0 {main}

ProfessorController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use View;
use App\Professor;
use Input;

class ProfessorController extends Controller
{
    public function getProfessorList()
    {
        return View::make('professor', [
            'professor' => Professor::all()
        ]);
    }

    public function postProfessorList()
    {
        Professor::submit(Input::post('disciplina'), input::post('professor'), input::post('old'));
    }
}

Professor Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class Professor extends Model
{
    protected $table = "professor";    

    public function disc()
    {
        return $this->belongsToMany('App\Disciplina');
    }

    public function scopeSubmit($disc, $professor, $old)
    {
        DB::insert('INSERT INTO disciplina_professor VALUES (`$disc`, `$professor`)');
        DB::delete('DELETE FROM disciplina_professor WHERE professor_id = `$old`');
    }

}

Ghaleon's avatar

@lancebutler2 Same error:

public function postProfessorList()
    {
        Professor::submit(Input::get('discipline'), input::get('professor'), input::get('old'));
    }
lancebutler2's avatar

Don't use lowercase i's in the other two Input class calls.

1 like
lancebutler2's avatar
Level 11

Seemingly, you fixed your csrf_token error (You HAD a mismatch error at one point). You're hitting your controller correctly now. You could simply return the whole request/input as a response and use chrome dev's network tools to make sure everything is received properly.

Now you're getting an Undefined method called because the Input class (an alias for Request) does not have a post() method. So Input::post() (or Request::post()) doesn't exist. It should be Input::get() (or Request::get())

Lastly, your using a query scope, and incorrectly, which will likely cause you to run into another error once your Undefined method called error is resolved.

1 like
Ghaleon's avatar

@lancebutler2 I'm getting over 100 errors now haha. Some of them about database query. Could you take a look and help me out find the source of the error ?

[2015-08-08 15:03:21] local.ERROR: exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column '$disc' in 'field list'' in F:\PathToProject\vendor\laravel\framework\src\Illuminate\Database\Connection.php:381 Stack trace: #0 F:\PathToProject\vendor\laravel\framework\src\Illuminate\Database\Connection.php(381): PDO->prepare('INSERT INTO dis...') #1 F:\PathToProject\vendor\laravel\framework\src\Illuminate\Database\Connection.php(629): Illuminate\Database\Connection->Illuminate\Database{closure}(Object(Illuminate\Database\MySqlConnection), 'INSERT INTO dis...', Array) #2 F:\PathToProject\vendor\laravel\framework\src\Illuminate\Database\Connection.php(596): Illuminate\Database\Connection->runQueryCallback('INSERT INTO dis...', Array, Object(Closure))

After creating the method to do it, how do I trigger it ?

public function update_table($disc, $professor, $old)
    {
        DB::insert('INSERT INTO disciplina_professor VALUES (`$disc`, `$professor`)');
        DB::delete('DELETE FROM disciplina_professor WHERE professor_id = `$old`');
    }
lancebutler2's avatar

@Ghaleon The first line in that stack trace explains the error. Unknown columns $disc in field list.

You used single quotes in both your insert and delete statements. PHP won't parse that as a variable.

1 like
Ghaleon's avatar

@lancebutler2 Thanks !

Somehow it's taking the ID value as one column.

public static function atualiza_drag($disc, $professor, $old)
    {
        DB::insert("INSERT INTO disciplina_professor (disciplina_id, professor_id) VALUES (`$disc`, `$professor`)");
        DB::delete("DELETE FROM disciplina_professor WHERE professor_id = `$old`");
    }

'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column '5' in 'field list'

5 is the ID that I want to use as parameter in the query.

willvincent's avatar

You're also going to need to update that delete query, unless you're wanting to remove ALL disciplines from the old professor.. add a second condition to your where clause to also match the discipline id. ;)

1 like
Francismori7's avatar

When inputing values with SQL, do not use ` (acute accent, those are for symbols, like columns), instead, use quotes (", ').

1 like
Ghaleon's avatar

Thanks so much for everyone !! Really appreciate your help guys.

@willvincent Yeah, I saw that yesterday when I moved the item and the whole sublist was deleted hahahaha.Thanks buddy!

Francismori7's avatar

@Ghaleon also, instead of running two queries (insert-delete), why not run an UPDATE? Just change the professor_id for the discipline you are looking to move?

My two cents.

2 likes
Next

Please or to participate in this conversation.