我正在尽一切努力使我的网页更流畅。事实是,我试图提交一个JQuery,现在,按下按钮时什么也没做。
这是我的代码:
The form:
<form id="myForm">
<div class="author-thumb">
<img src="{{ Auth::user()->getFirstMediaUrl('pps') ? Auth::user()->getFirstMediaUrl('pps') : '/img/ava_10.jpg' }}" width="36" height="36" alt="author">
</div>
<div class="form-group with-icon label-floating is-empty">
<label class="control-label">Share what you are thinking here...</label>
<textarea class="form-control" name="content" id="content" required></textarea>
</div>
<div class="add-options-message">
<a href="#" class="options-message" data-toggle="tooltip" data-placement="top" data-original-title="ADD PHOTOS">
<svg class="olymp-camera-icon" data-toggle="modal" data-target="#update-header-photo"><use xlink:href="icons/icons.svg#olymp-camera-icon"></use></svg>
</a>
<button class="btn btn-primary btn-md-2" id="ajaxSubmit">Post</button>
</div>
</form>
The controller:
public function store(Request $request)
{
$post = new Post();
$post->user_id = Auth::user()->id;
$post->username = Auth::user()->username;
$post->author = Auth::user()->name;
$post->content = $request->content;
$post->save();
return response()->json(['success'=>'Data is successfully added']);
}
The route:
Route::post('/post', [
'uses' => 'PostController@store',
]);
The JQuery:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#ajaxSubmit').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/post') }}",
method: 'post',
data: {
content: jQuery('#content').val()
},
success: function(result){
console.log(result);
}});
});
});
</script>
有人可以帮我吗?请向我解释代码的哪一部分是错误的,以及如何避免再次发生相同的错误。预先感谢您的宝贵时间。
答案 0 :(得分:0)
解决方案如下:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#ajaxSubmit').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/post') }}",
method: 'post',
data: {
_token: '{{csrf_token()}}', <-- ADD THIS LINE!
content: jQuery('#content').val()
},
success: function(result){
console.log(result);
}});
});
});
</script>