Laravel 5: Ajax Post 500 (Internal Server Error)

前端 未结 5 814
终归单人心
终归单人心 2020-12-10 07:54

I\'m trying to submit data to the database via ajax. The submit article page works fine without ajax. I\'ve added console.log() just to see if anything is going

5条回答
  •  臣服心动
    2020-12-10 08:15

    When you make a request via POST to a resource controller, it automatically calls store method:

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

    So, you just need to change ajax url to:

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

    When you need to send the session token, you can add a global meta-tag like this is you website:

    
    

    Then, just add the token via ajax's headers:

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

    If you are using Form::open() function (LaravelCollective) it adds a hidden input with the token as value with the name _token. So, you can remove the meta-tag and edit your ajax's headers like this:

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

提交回复
热议问题