最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass data from ajax to laravel 5.2 controller via post method - Stack Overflow

programmeradmin4浏览0评论

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 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

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

Share Improve this question edited Nov 13, 2017 at 11:39 Don't Panic 14.5k5 gold badges34 silver badges53 bronze badges asked Mar 22, 2016 at 19:12 FortuneFortune 1,6053 gold badges21 silver badges25 bronze badges 1
  • have you been able to confirm that the data is indeed being posted to the desired route? For example, in your browser console, which HTTP response code do you get when you post the data? Have you tried dumping the contents of $request directly in your controller? – alexw Commented Mar 22, 2016 at 19:30
Add a comment  | 

5 Answers 5

Reset to default 10

Your AJAX is POSTing, but you have no POST route set, only GET. Add a POST route, like so:

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

First check with your developer/network tool (eg. firebug) wether your ajax call reaches the desired controller/functions and that the parameters are forwarded correctly.

A safe way to specify Url in the ajax call in the Laravel environment is using the URL facade like this:

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

In order to do it like this however you must store your js as a myscript.blade.php (!!) file and @include it into your view accordingly.

For receiving your posted parameters in the controller function there is no need to declare function arguments, you can simply use the Input::Get() function eg. like this:

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

If you try to do POST request you may need to have X-CSRF-Token.

Add this to meta:

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

And setup your AJAX:

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

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

First you need set up dataType for ajax request like this (if you using jQuery)

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

then try use into your controller as follow

Request::json()

and see result

Also you may use Input::get() :

Request::get('userID')

you can use route name to pass 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)

  1. 暂无评论