Ajax Post 在 Laravel 5.1 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32203564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:15:18  来源:igfitidea点击:

Ajax Post not Working in laravel 5.1

phplaravellaravel-5laravel-5.1

提问by scott

I am trying to post data using ajax in laravel but it seems to be not working. I have followed following is my code

我正在尝试在 laravel 中使用 ajax 发布数据,但它似乎不起作用。我遵循以下是我的代码

login.blade.php

登录名.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf_token" content="{{ csrf_token() }}" />

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> 
<style type="text/css">

</style>
<script type="text/javascript">
$(document).ready(function(){
  $('.send-btn').click(function(){   
  console.log($('input[name=email]').val());
    $.ajax({
      url: 'login',
      type: "post",
      data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val()},
      success: function(data){
      console.log($('input[name=email]').val());
        alert(data);
      }
    });      
  }); 


});
</script>
</head>
<body>
<div class="secure">Secure Login form</div>
{!! Form::open(array('url'=>'account/login','method'=>'POST', 'id'=>'myform')) !!}
<div class="control-group">
  <div class="controls">
     {!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email')) !!}
  </div>
</div>
<div class="control-group">
  <div class="controls">

  </div>
</div>
{!! Form::button('Login', array('class'=>'send-btn')) !!}
{!! Form::close() !!}
</body>
</html>                                     

and route.php

和 route.php

Route::get('account/login', function() {
  return View::make('login');
});
Route::post('account/login', 'AccountController@login');

and in controller

并在控制器中

 public function login() {
    // Getting all post data
    if(!Request::ajax()) {
      $data = Input::all();
      print_r($data);
    }

    }

Whenever I try to submit form not working. I tried using alert in onclick jquery but it shows alert message. Can anyone tell why it's not working?

每当我尝试提交表单不起作用时。我尝试在 onclick jquery 中使用警报,但它显示警报消息。谁能告诉为什么它不起作用?

Note: This question already asked but not found any answer useful for me

注意:这个问题已经问过了,但没有找到任何对我有用的答案

Laravel 5.1 ajax not working?

Laravel 5.1 ajax 不工作?

Update

更新

<script type="text/javascript">
$(document).ready(function(){
  $('.send-btn').click(function(){   
  console.log($('input[name=email]').val());
    $.ajax({
      url: 'login',
      type: "post",

      data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val(),'_method': 'POST'},
      success: function(data){
      console.log($('input[name=email]').val());
        alert(data);
      }
    });      
  }); 


});
</script>

In console security i get following error

在控制台安全中,我收到以下错误

 [HTTP/1.0 500 Internal Server Error 115ms]


Update 2


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf_token" content="{{ csrf_token() }}">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> 
<style type="text/css">

</style>

<script>
$(document).ready(function() {
    $('#frm').on('submit', function (e) {
    alert();
        e.preventDefault();
        var title = $('#title').val();
        var body = $('#body').val();
        var published_at = $('#published_at').val();
        $.ajax({
            type: "POST",
            url: 'http://localhost/demo/public/articles/articles',
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
            dataType: 'JSON',
            data: {title: title, body: body, published_at: published_at},
            success: function( data ) {
                $("#ajaxResponse").append(data.msg);
                alert(data);
            }
        });
    });
    });
</script>
</head>
<body>

{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
    <p>
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title') !!}
    </p>

    <p>
        {!! Form::label('body', 'Body:') !!}
        {!! Form::textarea('body') !!}
    </p>

    <p>
        {!! Form::label('published_at', 'Date:') !!}
        {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
    </p>

    <p>
        {!! Form::submit('Submit Article', ['id' => 'submit']) !!}
    </p>
{!! Form::close() !!}

</body>
</html>   

route.php

路由文件

Route::resource('articles', 'ArticlesController');

Article controller

文章控制者

public function store()
    {
        print_r(Request::all());

    }

enter image description here

在此处输入图片说明

Update 2

更新 2

[2015-08-28 06:23:03] 

local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53
Stack trace:
#0 [internal function]: Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#1 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#2 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php(54): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#3 [internal function]: Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#4 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#5 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(62): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#6 [internal function]: Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#7 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#8 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#9 [internal function]: Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#10 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#11 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php(59): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#12 [internal function]: Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#13 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#14 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php(42): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#15 [internal function]: Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#16 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#17 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#18 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#19 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(122): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#20 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(87): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#21 D:\xampp\htdocs\demo\public\index.php(54): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#22 {main}  

回答by Afraz Ahmad

You are doing multiple mistakes:

你犯了很多错误:

1-your csrf token is in meta tag (not in input field):

1-您的 csrf 令牌在元标记中(不在输入字段中):

2-meta tag name is csrf_token (but you are calling it with wrong name i.e _token)

2-meta 标签名称是 csrf_token(但你用错误的名称调用它,即 _token)

3- csrf token is not in value attribute but it is in content attribute

3- csrf 令牌不在 value 属性中,但在 content 属性中

So you have to call it like this

所以你必须这样称呼它

_token': $('meta[name=csrf_token]').attr('content')

Anyhow There is much easier way to do this as shown below:

无论如何,有更简单的方法可以做到这一点,如下所示:

 _token:"{{csrf_token()}}"

No need of it:

不需要它:

_token: $('meta[name=csrf_token]').attr('content')

Use this statement instead:

请改用此语句:

_token:"{{csrf_token()}}" will do the same.

Full Example:

完整示例:

$.ajax
        ({
            type: "POST",
            dataType : 'json',
            url: "{{route('routeName')}}", 
            data: {_token:"{{csrf_token()}}", data: data}
        }).done( function(data){
            console.log('Ajax was Successful!')
            console.log(data)
        }).fail(function(){
            console.log('Ajax Failed')
        });

回答by ChainList

The form is perfectly working.

该表格是完美的工作。

You just forget to send "_method": "post"in your ajax form data. Laravel is using Symfony routing which uses a special parameter called _ methodto route to your route definition.

您只是忘记发送"_method": "post"ajax 表单数据。Laravel 正在使用 Symfony 路由,它使用一个名为_方法的特殊参数来路由到您的路由定义。

回答by manix

What I see is a wrong url called in ajax definition, should be:

我看到的是在 ajax 定义中调用的错误 url,应该是:

url: 'http://localhost/demo/public/articles',

The url above should store an article. For post login you should use:

上面的 url 应该存储一篇文章。对于登录后,您应该使用:

url: 'http://localhost/demo/public/login',

As a note, if your website will change the domain url, you could initialize the url via javascript in the header:

请注意,如果您的网站将更改域 url,您可以通过标题中的 javascript 初始化该 url:

<script>
    var login_url = '{{ url("login") }}';
</script>

Then you can call it as:

然后你可以称之为:

$.ajax({
        type: "POST",
        url: login_url,

回答by madpoet

As you can see from the exception, you're having a problem with the CSRF token. So somehow you are not able to send the token, that's what you must track down.

从异常中可以看出,CSRF 令牌存在问题。所以不知何故你无法发送令牌,这就是你必须追踪的。

In the original question before the updates, you're sending the token from the hidden form element like: '_token': $('input[name=_token]').val()

在更新之前的原始问题中,您从隐藏的表单元素发送令牌,例如: '_token': $('input[name=_token]').val()

Form::openis supposed to add the field in the form but probably there was a problem the so I'd advise you to view the source of the page to make sure that there is a hidden form element like <input type="hidden" name="_token" value="asdfasfd">.

Form::open应该在表单中添加该字段,但可能存在问题,因此我建议您查看页面的源代码以确保存在隐藏的表单元素,例如<input type="hidden" name="_token" value="asdfasfd">.

And/or you can just type $('input[name=_token]').val()in your browser's console to make sure that you can reach the value.

和/或您只需$('input[name=_token]').val()在浏览器的控制台中输入以确保您可以达到该值。



After 'update 2' you decided to move the CSRF token to the meta tag and send it with headers but the name of the meta is csrf_tokenhowever you're referencing it in the $.ajax options as csrf-token(dash instead of underscore is used).

在“更新 2”之后,您决定将 CSRF 令牌移动到元标记并将其与标头一起发送,但是元的名称是csrf_token您在 $.ajax 选项中引用它作为csrf-token(使用破折号而不是下划线)。



For both of the cases, best way to track down the issue is using your browsers console effectively:

对于这两种情况,追踪问题的最佳方法是有效地使用浏览器控制台:

  • When you see the error in the console, just click on the link and it'll take you to the "network" tab.
  • You'll see all the requests in there, find your request by looking at the name and click it. (It should be highlighted for a moment but sometimes it's not visible so you might need to scroll up or down to find it).
  • At the right side click on "headers" tab and scroll down to see the _tokenfield -or- X-CSRF-TOKENheader and if they're empty or not.
  • Another tip is, click on "response" or "preview" tab to see the server response, it's quicker to detect the error that way instead of going to the logs etc.
  • 当您在控制台中看到错误时,只需单击链接,它就会将您带到“网络”选项卡。
  • 您将在其中看到所有请求,通过查看名称找到您的请求并单击它。(它应该突出显示片刻,但有时它不可见,因此您可能需要向上或向下滚动才能找到它)。
  • 在右侧单击“标题”选项卡并向下滚动以查看_token字段 -X-CSRF-TOKEN或-标题以及它们是否为空。
  • 另一个提示是,单击“响应”或“预览”选项卡以查看服务器响应,这样可以更快地检测错误,而不是查看日志等。

回答by DonnaJo

I'm noticing a couple of things right off the bat. First and foremost, you have set your POST route (in routes.php) to 'account/login', but you are setting your $.ajax url to 'login'. You need to set it to '/account/login', just like you have it in your form url and (most importantly) routes file.

我立即注意到一些事情。首先,您已将 POST 路由(在 routes.php 中)设置为“帐户/登录”,但您将 $.ajax url 设置为“登录”。您需要将其设置为“/account/login”,就像您在表单 url 和(最重要的)路由文件中拥有它一样。

Also, because you are using the Laravel {!! Form::xxx() !!} structure, you do not need to include 'method'=>'POST'. That will be added for you automatically, as will the CSRF Token. http://laravelcollective.com/docs/5.0/html#opening-a-form

另外,因为您使用的是 Laravel {!! Form::xxx() !!} 结构,不需要包含'method'=>'POST'。它将自动为您添加,CSRF 令牌也是如此。http://laravelcollective.com/docs/5.0/html#opening-a-form

Also, the 'login' function in your Controller is only running if the request is notAJAX, but you're trying to send through an AJAX request, correct? Just a couple of things to delve into. Hope it helps.

此外,控制器中的“登录”功能仅在请求不是AJAX时才运行,但您尝试通过 AJAX 请求发送,对吗?只需深入研究几件事。希望能帮助到你。

回答by Nico Orfi

I think that the problem is in App/Http/Middleware/Authenticate.phpTry changing this

我认为问题出在App/Http/Middleware/Authenticate.php尝试改变这个

public function handle($request, Closure $next)
{
    if ($this->auth->guest())
    {
        if ($request->ajax())
        {
            return response('Unauthorized.', 401);
        }
        else
        {
            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}

To this:

对此:

public function handle($request, Closure $next)
{
    return $next($request);
}

回答by Gregory Bowers

The problem is that you are using a URL instead of a direct path. Laravel pretty much overrides and redirects anything http post or get. Open up your browsers developer tools and look at the request, the URL that was actually requested is different than the one in your ajax call.

问题是您使用的是 URL 而不是直接路径。Laravel 几乎覆盖和重定向任何 http post 或 get。打开浏览器开发者工具查看请求,实际请求的 URL 与 ajax 调用中的 URL 不同。

See example below, full URL DOES NOT WORK. Absolute path does.

请参见下面的示例,完整的 URL 不起作用。绝对路径确实如此。

$.ajax
        ({
            type: "POST",
            dataType : 'text',
            url: "../../public/head-editor-api/index.php", 
            data: {
                website_hosting_server: website_hosting_server,
                website_hosting_username: website_hosting_username,
                website_hosting_password: website_hosting_password
            }
        }).done( function(data){
            alert(data);
        }).fail(function(){
           alert("error");
        });