How to pass data from ajax to laravel 5.2 controller via post method

Viewed 16935

Hello StackOverflow family. This is my very first question and I hope to get help.

I'm new to laravel framework and am using version 5.2 in my project. Am trying to pass data using the post method from my ajax function to a particular controller method but no data is passed to the controller.

I followed the steps in this forum https://laracasts.com/discuss/channels/laravel/process-data-in-controller-using-ajax-in-laravel but can't get it to work. Here is what I've done so far.

My JavaScript (post_script.js):

$.ajax({
    method: 'POST',
    url: './home',
    data: {
        userID: 76,
        userName: 'Jimmy'
     },
});

Note that this file is saved in assets/js directory in the laravel structure. Here is what I have in my route file (routes.php):

Route::get('/', "MyController@home");
Route::get('home', "MyController@home");

Here is the function I have in MyController.php file:

function home(Request $request) {
    $userID = $request['userID'];
    $userName = $request['userName'];
    return view('home', [
      'userID'=> $userID,
      'userName' => $userName
    ]);
}

In my view, I tried to access it like this:

<p>User ID: {{$userID}}</p>
<p>User Name: {{$username}}</p>

Nothing is displayed! Please what am I doing wrong? I need your help. Forgive me if my question is not proper but I hope you get what I mean. Thank you

5 Answers
Related