2
votes

I'm trying to make a POST to

http://localhost:8888/test


JS

$('.saveBTN').click(function (event) {

    $( "form#editForm" ).on( "submit", function( event ) {
      event.preventDefault();

      var inputs = {};
      $("#editForm :input").each(function() {
        inputs[$(this).attr("name")] = $(this).val();
      });

      var $inputs = JSON.stringify(inputs);

      $.ajax({
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
          url: '/test',
          type: 'POST',
          dataType: 'json',
          data: $inputs,
          success: function (data, textStatus, xhr) {

              console.log(data);
          },
          error: function (xhr, textStatus, errorThrown) {

              console.log('PUT error.');
          }
      });

});

I keep getting

500 Internal Server Error

I've tried added

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

and this on my Ajax

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

Any hints on this will be much appreciated !

2
Fire up the inspector have a look at the full details of the 500 response that would give you a better idea of what is going on. A guess is routing you say PUT error in your error handling but are making a POST request are you looking for a PUT on your route? - Mark Davidson
What does your routing look like? - camelCase
can you check the log file in storage folder for error stack? - Vikas
500 error means the script on the server is getting an error. Check your server log. - Barmar

2 Answers

7
votes

Add this in below inside the form.

// This will generate token field which will be token
{{ csrf_field() }}  


// Expected Output
<input type="hidden" name="_token" value="ssdfdsfsdfsdfs32r23442">

VerifyCsrfToken.php - The File is middleware, which is included in the web middleware group, will automatically verify that the token in the request input matches the token stored in the session.

Refer this URL for few more information: http://laravel.com/docs/master/routing#csrf-x-csrf-token

Updates - 23rd Dec 2016

As of laravel, you can use like below as well.

<form action="/foo/bar" method="POST">
    <input type="hidden" name="_method" value="POST">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

API Reference: https://laravel.com/docs/master/routing#form-method-spoofing

0
votes

Like @Paulpro and @Mark Davidson mentioned in comments bellow the meta tag should have content attribute and not value :

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

Instead of :

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

Hope this helps.