Halnex Halnex - 10 months ago 135
Ajax Question

Laravel 5: Ajax Post 500 (Internal Server Error)

I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added

just to see if anything is going through, but instead I'm getting this error:

POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)

What's wrong with my code? Is it the javascript or the controller?

EDIT: I'm getting this in

exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53


Route::resource('articles', 'ArticlesController');


public function store(Requests\ArticleRequest $request)

$article = new Article($request->all());

$response = array(
'status' => 'success',
'msg' => 'Article has been posted.',
return \Response::json($response);


$(document).ready(function() {
$('#frm').on('submit', function (e) {
var title = $('#title').val();
var body = $('#body').val();
var published_at = $('#published_at').val();
type: "POST",
url: 'http://localhost/laravel-5/public/articles/create',
dataType: 'JSON',
data: {title: title, body: body, published_at: published_at},
success: function( data ) {


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<h1>Write a New Article</h1>


{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title') !!}

{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body') !!}

{!! Form::label('published_at', 'Date:') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}

{!! Form::submit('Submit Article', ['id' => 'submit']) !!}
{!! Form::close() !!}

<h3 id="ajaxResponse"></h3>

@foreach($errors->all() as $error)
<li>{{ $error }}</li>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>



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:

        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:

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

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

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

If you are using HTML::form() 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:

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