How to transfer data from ajax to laravel 5.2 controller via mail method

Hello StackOverflow Family This is my first question, and I hope to get help.

I am new to the laravel framework and am using version 5.2 in my project. I am trying to pass data using the post method from my ajax function to a specific controller method, but the data is not being transferred 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 could not get it to work. Here is what I have done so far.

My JavaScript ( post_script.js):

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

Note that this file is stored in a directory assets/jsin the laravel structure. Here is what I have in the route ( routes.php) file :

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

, MyController.php:

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

, :

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

! , ? . , , , , .

+4
5

AJAX POSTING, POST, GET. POST-, :

Route::post('home', "MyController@home");
+8

/ (, firebug), ajax / .

Url ajax Laravel URL-, :

url: "{{ URL::to('home'); }}",

, js myscript.blade.php(!!) @ .

, Input:: Get(), . :

public function home()
{
  $userID = Input::Get('userID');
  $userName = Input::Get('userName');
  return view('home', [ 'userID'=> $userID, 'userName' => $userName ]);
}
+3

POST, X-CSRF-Token.

:

<meta name="csrf-token" content="{{ csrf_token() }}">

AJAX:

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

Laravel: https://laravel.com/docs/5.2/routing#csrf-x-csrf-token

+1

dataType ajax ( jQuery)

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

,

Request::json()

Input:: get():

Request::get('userID')
0

you can use the route name to transfer your data to the controller

 $.ajaxSetup({
            headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
        });
        $.ajax({
            type:'POST',
            url: '{{route("route_name_with_post_method")}}',
            data:{
              'id': data
            },
            success:function(r){

            },error:function(r) {

            }
        });
0
source

All Articles