TokenMismatchException in VerifyCsrfToken sending ajax by POST. ERROR 500

1

Hi, I have a problem with the csrftoken when making an ajax request.

If I deactivate it in the kernel,

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
         //   \App\Http\Middleware\VerifyCsrfToken::class,

It makes the request correctly, inserts the code well and displays the messages perfectly, but if I do not deactivate it (as it should be), it throws a 500 error in each ajax request, and puts me on top of each request. The idea is to enter values in the database by ajax. The error it throws is this.

TokenMismatchException in VerifyCsrfToken

VISTA

    @if(count($errors))
                        <div class="alert alert-danger">
                            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>

                        @foreach($errors->all() as $errores)
                            <p><strong>{{$errores}}</strong></p>
                        @endforeach
                        </div>
                    @endif

{!! Form::open(array('route'=>'pruebaControlador.store','method'=>'POST'),array('id'=>'formularioajax')) !!}

                <div class="form-group">

                     {!! Form::label('', 'Nombre',array('id'=>'labelnombre')) !!}

                    {!! Form::text('nombre', old('nombre'), ['class'=>'form-control']) !!}
                    {!!Form::token()!!}

                </div>

                <div class="form-group" id="ajaxdiv" >

                </div>

    {!! Form::submit('Validar Campos', ['id'=>'botonsubmit','class'=>'btn btn-default']) !!}

        {!! Form::close() !!}

FUNCIONES.JS

$('document').ready(function(){
        $('body').css('background','maroon');
        var ruta_completa= window.location.pathname;
        $('#botonsubmit').before(ruta_completa);

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

        $('#botonsubmit').click(function(e){


            e.preventDefault();
                var nombre = $('input[name="nombre"]').val();
                var tokenvalue = $('input[name="_token"]').val();
                console.log(nombre);
                console.log('<br/>'+tokenvalue);

            $.ajax({

            url : ruta_completa,
            data : {'nombre': nombre,
                    //'_token':  tokenvalue
                },
            method: 'POST',

                    })
            .done(function(data) {
                console.log("success");
                var estilo = 'style="background : green; height : 30px; text-align:center; color:white; margin-top:20px "';
                var msgnotificacion =   '<div class="alert alert-success">';
                        msgnotificacion+=   '<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>';
                        msgnotificacion+=   '<strong>REGISTRO '+nombre+' INSERTADO CORRECTAMENTE</strong>';
                    msgnotificacion+=   '</div>';

                     $('#labelnombre').after(msgnotificacion);
                     $('#botonsubmit').after('<p '+estilo+'>Nombre ..:: '+nombre+' ::.. </p>');

                            })
            .fail(function(jqXHR,thrownError) {
                console.log("error "+jqXHR.status);
                 if(xhr.status==404) {
                     console.log(thrownError);
                            }

                            })
            .always(function() {
                console.log("complete");
                            });
        });


    });

ROUTES

Route::resource('pruebaControlador','PruebaController');

PRUEBACONTROLLER

(I've removed the empty methods)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Requests\validaFormulario;
use Validator;

class PruebaController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        return view('pruebas.index');

    }

    public function store(validaFormulario $formulario)

    {


        $datosUsuarios = array(
                    'name' => $formulario->nombre,
                    'email' => 'default_'.rand(5555555,99999999).'@default.com',
                    'password' => bcrypt('1'),
            );

        \App\user::create($datosUsuarios);

        return response()->json($formulario->all());


    }

}

VALIDFORMULAR

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class validaFormulario extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'nombre' => 'required|min:2',
        ];
    }

    public function messages()
    {
        return array(
                    'nombre.required' => 'El campo :attribute es requerido',
                    'nombre.min' => 'El campo :attribute tiene un minimo de caracteres requeridos de 2 caracteres',
                );
    }
}

/ ********************** OTHER RELATED ERROR **************** *********************** /

Regardless of whether or not the csrf token is active, it does not show the messages that I specified in the view with this code

@if(count($errors))
                            <div class="alert alert-danger">
                                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>

                            @foreach($errors->all() as $errores)
                                <p><strong>{{$errores}}</strong></p>
                            @endforeach
                            </div>
                        @endif

This, if I do it sending the form without ajax works perfectly but with ajax it does not show the errors .... although it does the validation (validaFormulario in controller store, CUSTOM REQUEST), that is to say if the field is empty, no shows nothing but does not insert anything in the database

    
asked by KurodoAkabane 06.09.2016 в 18:51
source

2 answers

1

You have to add the respective field to <head> of the view involved:

@push('head')
  <meta name="_token" content="{!! csrf_token() !!}"/>
@endpush

This assuming you have something like that in your "global" template:

<head>
  @stack('head')
</head>

The rest is similar to what you already have:

Scripts at the end of the web page:

    $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
    });
    
answered by 07.09.2016 / 00:10
source
1

Try adding this to your form:

<input type="hidden" name="_token" value="{{ csrf_token() }}">

EDIT

In this post I found you detail how to verify your ajax form

link

I hope I help you

    
answered by 06.09.2016 в 19:06