0

I'm developing an application with Laravel 5.1 and I have a problem when sending ajax petition I have the next code:

View for Create:

{!!Form::open()!!}

    <div class="form-group">
   {!!Form::label('genero','Genre:')!!}
   {!!Form::text('genre',null,['id'=> 'genre','class'=>'form-control'])!!}
    </div>

    {!!link_to('#', $title = 'Create', $attributes = ['id'=> 'create','class'=>'btn btn-primary'], $secure = null)!!}
{!!Form::close()!!}

Ajax Petition:

$("#create").click(function(){
 var genre = $("#genre").val();
 var route = "http://localhost:8000/genre";
 $.ajax({
   url: route,
   type: 'POST',
   dataType: 'json'
   data: {genre : genre}
  });
})

In my Routes:

Route::resource('genre','GenreController');

But when send the petition I have the next error:

POST http://localhost:8000/genre 500 (Internal Server Error)

Thanks.

Roham Rafii
  • 2,929
  • 7
  • 35
  • 49
Lagul
  • 199
  • 1
  • 6
  • 19
  • Check your php error log. The reason for the error will be in there most likely – MiltoxBeyond Jul 14 '15 at 20:47
  • into the console (Preview) I have the next error : TokenMismatchException in VerifyCsrfToken.php line 53: – Lagul Jul 14 '15 at 20:55
  • 1
    TokenMismatch can be fixed by adding the header to your ajax post method. If you are creating the javascript in the view you can put the value in the ajax parameter. `headers: { 'X-XSRF-TOKEN': {{ Session::token() }} } ` – MiltoxBeyond Jul 14 '15 at 21:01
  • This answer may help: http://stackoverflow.com/questions/28500525/laravel-5-csrf-global-token-hidden-field-for-all-forms-in-a-page – MiltoxBeyond Jul 14 '15 at 21:02
  • I add into my view the token : {!! Form::token() !!} and add the headers into my petition ajax headers: { 'X-XSRF-Token': $('meta[name="_token"]').attr('content') } but i have the same error u.u – Lagul Jul 18 '15 at 15:35

2 Answers2

1

In default template , add meta tag

<meta name="_token" content="{!! csrf_token() !!}"/>

Then add script code :

<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>

Then you can use ajax call...as normal

shalini
  • 1,291
  • 11
  • 13
0

My solution was the next code:

$("#registro").click(function(){
var data = $("#genre").val();
var route = "http://localhost:8000/genre";
var token = document.getElementById('token').value

$.ajax({
  url: route,
  headers: {'X-CSRF-TOKEN': token},
  type: 'POST',
  dataType: 'json',
  data: {data : data}
 });
});
Lagul
  • 199
  • 1
  • 6
  • 19