Problem with sending data by ajax (laravel)

1

I am sending a data by ajax with type: 'post', but it generates an error, when I change it to type: 'get', the data is received in success. This is the code.

Ajax

$('.QuestionList-item').on('click', function() {
        $('.Question').show();
        $('.QuestionList').removeClass('col-12').addClass('col-6');

        var param = {
            '_token'  : $('#token').val(),
            'userid': $(this).children('.clientName').val()
        };

        $.ajax({
            url     :  "{{route('questionDetail')}}",
            type    :  'post',
            dataType:  'json',
            data    :   param,
            success :   function (data) {
                alert('send');
            },
            error   :   function() {
                alert('error');
            }
        });
    });

Blade

@foreach($questions as $question)
    <article class="QuestionList-item row middle">
        <figure class="stateIcon">
            <svg title="checkmark" viewBox="0 0 32 32" class="svgIcon detailsTitle-checkmarkSvg"><polygon points="30,5.077 26,2 11.5,22.5 4.5,15.5 1,19 12,30"></polygon></svg>
        </figure>
        <span class="ProductName">{{$question->product->name}}</span>
        <input class="clientName" type="text" value="{{$question->user_id}}">
    </article>
@endforeach

Route

Route::post('preguntas', [
'uses' => '[email protected]',
'as' => 'questionDetail',
'middleware' => 'VerifyProvider']);

Driver

function questionDetail(Request $request){
    if($request->ajax()){
        $user = User::find(1);
        return response()->json([$user]);
    }
}
    
asked by Santiago Ruiz 07.05.2016 в 18:00
source

2 answers

2

I have already solved the error. To send by the post method, in laravel the token is necessary. I forgot to put it on blade.

<input id="token" type="hidden" name="_token" value="{{ csrf_token() }}">
    
answered by 07.05.2016 / 18:03
source
1

After starting the event, you put this:

event.preventDefault();
$.ajaxSetup({headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content')}  })
    
answered by 06.06.2016 в 20:16