I'm working with Laravel 5 and I've the following code
HTML
<div id="row">
<textarea class="form-control" rows="3" id="comment" placeholder="Update your Post"></textarea>
</div>
<a href="#" id="btn-post" dusk="postButton" class="btn btn-primary" role="button" data-toggle="modal" data-target="#addPost">
<span class="ion-plus-circled"> Post</span>
</a>
JS
$(document).ready(function(){
$("#btn-post").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var comment = $('textarea#comment').val();
var postData = {
post_content: comment.val();
groupId: window.location.href.split("/")[4] // hack to get group id
}
console.log(postData);
$.ajax({
type: "POST",
url: "/post",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status){
$("#addPost").modal('toggle');
//window.location.href = data.redirectTo;
}
});
});
});
web.php
Route::post('post', 'GroupController@post');
GroupController.php
public function post(Request $request){
$post_content = $request->input('post_content');
$userId = Auth::user()->id;
$groupId = $request->input('groupId');
$post = PostGroup::firstOrNew(['group_id' => $groupId, 'post_content' => $post_content]);
$post->user_id = $userId;
$post->save();
$redirectPath = '/groups/' . $groupId;
return response()->json(['message' => 'Your post have been published! Take a look at',
'redirectTo' => $redirectPath]);
}
What I want to do is to call the javascript function "btn-post" at the click of the link-button "Post". This function takes the content of the textarea (which I don't know if I wrote correctly) and sends it to the GroupController using the same javascript function, to the route "/post", calling the function "post" (as defined in web.php), but for some reason it doesn't work, and I don't know where I was wrong (I think the problem is in the javascript function, as if it weren't called).
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HRsxU4
via IFTTT
Aucun commentaire:
Enregistrer un commentaire