A
A
axblue2016-11-23 17:36:43
JavaScript
axblue, 2016-11-23 17:36:43

How to send data via Ajax in Laravel?

Hi all. Help me deal with Ajax on Laravel, I still can't send data.
ajax itself

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

$('#recipe_comments').on('submit', function(e) {
    e.preventDefault();
    var text = $('.text').val();
    $.ajax({
        type: "POST",
        url: '/add_comment',
        data: {text:text},
        success: function(param)
        {
            console.log(param);
        },
        error: function(msg){
            console.log('error');
        }
    });
});

<form class="form-horizontal" method="POST" id="recipe_comments" enctype = "multipart/form-data">
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <textarea class="form-control text" rows="4" placeholder="Ваш отзыв"></textarea>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>

Route::post('/add_comment', '[email protected]');

class CommentsController extends Controller
{
    public function addComment(Request $request) {
        if($request->ajax()){
            $comment = new Comment();
            $comment->text =  Input::get('text');
            $comment->date = Carbon::now();
            $comment->save();
            $response = array(
                'status' => 'success',
                'msg' => 'Setting created successfully',
            );
            return Response::json($response);
            return 'yes';
        }else{
            return 'no';
        }
    }
}

Error in console when submitting:
POST http://el-recipes/add_comment 500 (Internal Server Error)

Probably jambs with CSRF, but I'm not sure. Tell me how to track at what stage the failure occurs. Thank you. I would also like to know the best way to implement this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nimfus, 2016-11-23
@leshikgo

It is worth checking the logs and the meta tag to see if the token is added there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question