Reputation: 165
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).
Upvotes: 0
Views: 705
Reputation: 9942
You have a syntax and a logic error in your Javascript here:
var comment = $('textarea#comment').val();
var postData = {
post_content: comment.val();
groupId: window.location.href.split("/")[4] // hack to get group id
}
Logic error: you assign textarea value to the var comment
. Then 2 lines after that, you call comment.val()
on it, although it's a string at this point. No need to call .val()
again.
Syntax error: you shouldn't use ;
within the postData
JSON definition. You separate JSON fields with a comma.
This is the fix for the above 2 problems:
var postData = {
post_content: comment, // <----
groupId: window.location.href.split("/")[4] // hack to get group id
}
I suggest you start using developer tools to debug your Javascript
Upvotes: 2