Laravel 5:Ajax Post 500(内部服务器错误)

时间:2015-08-27 18:31:55

标签: php jquery ajax laravel laravel-5

我试图通过ajax将数据提交到数据库。提交文章页面没有ajax工作正常。我已添加console.log()只是为了查看是否有任何问题,但我收到了此错误:

  

POST http://localhost/laravel-5/public/articles/create 500(内部服务器错误)

我的代码出了什么问题?是javascript还是控制器?

编辑:我在laravel.log

中收到此消息
  

exception' Illuminate \ Session \ TokenMismatchException'在C:\ xampp \ htdocs \ laravel-5 \ vendor \ laravel \ framework \ src \ Illuminate \ Foundation \ Http \ Middleware \ VerifyCsrfToken.php:53

路线

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

控制器

public function store(Requests\ArticleRequest $request)
    {

        $article = new Article($request->all());
        Auth::user()->articles()->save($article);

        $response = array(
            'status' => 'success',
            'msg' => 'Article has been posted.',
        );
        return \Response::json($response);
    }

的jQuery

$(document).ready(function() {
    $('#frm').on('submit', function (e) {
        e.preventDefault();
        var title = $('#title').val();
        var body = $('#body').val();
        var published_at = $('#published_at').val();
        $.ajax({
            type: "POST",
            url: 'http://localhost/laravel-5/public/articles/create',
            dataType: 'JSON',
            data: {title: title, body: body, published_at: published_at},
            success: function( data ) {
                $("#ajaxResponse").append(data.msg);
                console.log(data);
            }
        });
    });

查看

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<h1>Write a New Article</h1>

<hr>

{!! 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() !!}

<h3 id="ajaxResponse"></h3>

@if($errors->any())
    <ul>
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>

});

5 个答案:

答案 0 :(得分:13)

当您通过POST向资源控制器发出请求时,它会自动调用存储方法:

Verb    Path        Action  Route Name
----------------------------------
POST    /articles   store   articles.store

所以,你只需要将ajax url更改为:

$.ajax({
        type: "POST",
        url: 'http://localhost/laravel-5/public/articles',

当您需要发送会话令牌时,您可以添加一个全局元标记,例如这是您的网站:

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

然后,只需通过ajax的标题添加令牌:

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

如果您使用的是Form::open()函数(LaravelCollective),则会添加一个隐藏的输入,并将该标记作为值_token的值。因此,您可以删除元标记并编辑您的ajax标题,如下所示:

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('[name="_token"]').val()
        }
});

答案 1 :(得分:2)

  

这就是我在C:\ xampp \ htdocs \ laravel-5 \ vendor \ laravel \ framework \ src \ Illuminate \ Foundation \ Htt p \ Middleware \ VerifyCsrfToken.php中得到异常'Illuminate \ Session \ TokenMismatchException':53

你正在使用Laravel的CSRF保护。

http://laravel.com/docs/5.1/routing#csrf-protection

您需要传递隐藏的_token字段的值。这可以通过在应用程序的JS中执行此操作,在所有jQuery启动的AJAX请求上自动完成:

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('input[name="_token"]').value()
        }
});

或者,您可以在每个AJAX调用中手动获取并传递_token隐藏字段的值。

答案 2 :(得分:0)

我喜欢分享此代码以帮助某人需要ajax帖子并使用laravel

<<<<<<<<
POST
<<<<
<<look after @extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<< 
<<<------<<views\login\login.blade.php<<<<-----------<<<
@extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
@section('content')
  <form action="#" id="logForm" method="post" class="form-horizontal">
             <div class="form-group">
                <div class="col-xs-12">
                    <div class="input-group">
                        <input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">                            
                    </div>
                </div>
            </div>


            <div class="form-group">
                <div class="col-xs-12">
                    <div class="input-group">
                         <input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">

                    </div>
                </div>
            </div>
            <div class="form-group formSubmit">
                <div class="col-xs-12">
                    <div class="input-group">
                        <button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
                    </div>
                </div>
            </div>
     </form>

   <script type="text/javascript">
         $(document).ready(function () {
          $("#feedbackSubmit").click(function () {
              $.ajax({
                url: '{{URL::route('login4')}}',
                type: "post",
                 beforeSend: function (xhr) {
        var token = $('meta[name="csrf_token"]').attr('content');

        if (token) {
              return xhr.setRequestHeader('X-CSRF-TOKEN', token);
        }
    },
                data: $("#logForm").serialize(),
                success: function (data)
                {
                    if (data) {
                        alert(data);
                        console.log(data);
                         } else {
                  console.log(data);
                    }//else 
                }//success
              });//ajax
            return false;
          });//feedbacksubmit
   });//document ready
 </script>  
  -------------0----------------------
  -------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
 <?php
 use Illuminate\Http\Request;
 Route::post('login4', function()
{
    return 'Success! POST Ajax in laravel 5';
})->name('login4');

------------------0----------------------
------------------0----------------------
<<<<
Get
<<look after @extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<< 
<<<------<<views\login\login.blade.php<<<<-----------<<<
@extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
@section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
             <div class="form-group">
                <div class="col-xs-12">
                    <div class="input-group">
                        <input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">                            
                    </div>
                </div>
            </div>


            <div class="form-group">
                <div class="col-xs-12">
                    <div class="input-group">
                         <input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">

                    </div>
                </div>
            </div>
            <div class="form-group formSubmit">
                <div class="col-xs-12">
                    <div class="input-group">
                        <button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
                    </div>
                </div>
            </div>
 </form>


  <script type="text/javascript">
       $(document).ready(function () {
        $("#feedbackSubmit").click(function () {
              $.ajax({
                url: '{{URL::route('login2')}}',
                type: "get",

                beforeSend: function (xhr) {
        var token = $('meta[name="csrf_token"]').attr('content');
        if (token) {
              return xhr.setRequestHeader('X-CSRF-TOKEN', token);
        }
    },    

                data: $("#logForm").serialize(),
                success: function (data)
                {
                    if (data) {
                        obj = JSON.stringify(data, null, "    ");
                        var datito = JSON.parse(obj);
                        console.log(datito.response);
                        alert(datito.response);

                    } else {
                        console.log(data);
                    }//else 
                }//success
            });//ajax
            return false;
        });//feedbacksubmit
});//document ready
 </script> 
  -------------0----------------------
  -------------0----------------------
    <<<----<<app\Http\routes.php<<<<-----------<<<
    <?php
    use Illuminate\Http\Request;
    Route::get('login2', 'WebController@login2')->name('login2');
  -------------0----------------------
  -------------0----------------------
    <<<----<<Http\Controllers\WebController.php<<<<-----------<<<
   public function login2(Request $datos) {
    if ($datos->isMethod('get')) {
        return response()->json(['response' => 'This is get method']);
    }
    return response()->json(['response' => 'This is post method']);
}

  -------------0----------------------
  -------------0----------------------

答案 3 :(得分:0)

您可以将您的URL添加到VerifyCsrfToken.php中间件。这些网址将从CSRF验证中排除:

protected $except = [ "your url", "your url/abc" ];

答案 4 :(得分:0)

如果您正在寻找确定的答案,那么它是: 如果您在代码中缺少csrf_token(),则会发生此错误 这是我做的,

<h6>ITEMS  ORDERED:<a href="#" id="{{$post->identifier}}" onclick="getcart(this.id)">CLICK HERE</a></h6>
<input type="hidden" id="token" value="{{ csrf_token() }}">

现在使用Ajax

<script type="text/javascript">
function getcart(val) {
  var alpha=val;
var token=document.getElementById('token').value;

$.ajax({
 type:'post',
 url:'/private/getcart',
 data:{'alpha':alpha,'_token': token},//this _token should be as it is 
 success:function (result) {
alert(result);
 }

});


}

</script>

在我的laravel控制器

public function getcart(Request $req)
{
  return response ("its");
}