Send Form for create with AJAX and Laravel 5.1

2019-09-19 13:24发布

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.

2条回答
Root(大扎)
2楼-- · 2019-09-19 13:30

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}
 });
});
查看更多
疯言疯语
3楼-- · 2019-09-19 13:42

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

查看更多
登录 后发表回答