Ad

500 Internal Server Error Ajax Laravel

- 1 answer

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 !

Ad

Answer

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

Ad
source: stackoverflow.com
Ad