weixin_33716154 2017-07-16 20:37 采纳率: 0%
浏览 20

Laravel POST通过Ajax

I'm trying to submit a form via ajax, but I'm always getting internal server error

Here is my form code

{!! Form::open(['route' => 'users.add', 'id'=>'form']) !!}
<!-- Solo moderador -->
<div class="card-panel">
    @if(Auth::user()->permision->request == 1)
        <p class="center">Observaciones del moderador:</p>
        <textarea type="textarea" class="materialize-textarea" name="observations" id="updateObservations"></textarea> 
    @else
        <div class="center">
            <input type="checkbox" id="userVerify" class="filled-in">
            <label for="userVerify">Problema solucionado :)</label>
        </div> 
    </div>
    @endif 
{!! Form::close() !!}

Here is my route

Route::post('request/update', 'RequestsController@postUpdateRequest')->name('request.update');

Here is my Ajax method

$.ajax({
    type: "post",
    dataType: "html",
    url: 'request/update',
    data: $("#form").serialize(),
    success: function (response) {
        // write here any code needed for handling success         
        console.log("se envio");
    }
});

and here is my method in the controller

public function postUpdateRequest(Request $request)
{
    if($request->ajax())
    {
        // Obteniendo registro de la petición
        $petition = Petition::where('id', $request->id)->first();

        // Guardando
        $petition->fill($request->all());
        $auditConfirm = $petition->isDirty();
        $petition->save();

        // Guardando registro de auditoría
        if($auditConfirm){
            AuditsController::postAudit($this->action_id_update);
        }
    }

}

EDIT: This is the console output

  • 写回答

3条回答 默认 最新

  • weixin_33676492 2017-07-16 20:45
    关注

    Include this in your form:

     echo Form::token();
    

    Basically Laravel expects a CSRF token, middleware makes sure that token sent from form matches the token created before it.

    If you don't want to add that on forum, you can add that in AJAX setup:

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

    ..and have this in the HTML page header:

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

报告相同问题?