Send Form for create with AJAX and Laravel 5.1

醉酒当歌 提交于 2019-12-13 05:57:32

问题


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.


回答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




回答2:


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}
 });
});


来源:https://stackoverflow.com/questions/31416965/send-form-for-create-with-ajax-and-laravel-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!