Search code examples
ajaxlaravellaravel-5.3

Struggling to do a basic AJAX request in Laravel 5.3


I am trying to do a very basic AJAX request in Laravel, and it keeps giving me a 500 Internal Server Error. I attempted to add in the appropriate headers, but still no luck. Can anybody tell me what I am missing here?

My Route:

Route::get('/checkpin', 'EmployeeLoginController@checkPin');

My Controller:

<?php
    namespace App\Http\Controllers;

    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Http\Request;

    class EmployeeLoginController extends Controller {
        public function __construct() {
            $this->middleware('auth');
        }

        public function login(){
            $employees = DB::table('employees')->where([['clientID', '=', Auth::user()->userEmail]])->get();
            $adminEmployees = DB::table('employees')->where([['clientID', '=', Auth::user()->userEmail]]])->get();
            return view('auth/employee-login')->with(array('employees' => $employees, 'admins' => $adminEmployees));
        }

        public function checkPin($request) {

            if ($request->isMethod('post')){    
                return response()->json(['response' => 'This is post method']); 
            }

            return response()->json(['response' => 'This is get method']);
        }
    }

My AJAX:

$(".submit-key").click(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        type: "GET",
        url: "/checkpin",
        dataType: "json",
        data: "",
        success: function(response) {
            console.log(response);
        }
    });
});

As previously mentioned, whenever I hit the button, I get an error in my console that says 500 (Internal Server Error).

Does anybody have any idea what it is that I am missing?

Thanks!


Solution

  • I'll try, first try to remove / from the beginning of the route:

    Route::get('checkpin', 'EmployeeLoginController@checkPin');
    

    And add type casting to your function

    public function checkPin(Request $request) { ...
    

    Then it won't be treated as parameter.