Reputation: 327
The div containing the form, which is included in a post div
<div class="add-comment">
<form action="post.php?post=<?php echo $post->id; ?>" class="commentform" method="post">
<textarea name="content" class="comment_content"></textarea>
<input type="submit" class="submit" name="submit_comment" value="Add Comment" />
</form>
</div>
This is the code to handle the post
if(isset($_POST['submit_comment'])){
if(isset($_GET['post'])){
$content = strip_tags(trim($_POST['content']));
$comment = Comment::make($_GET['post'],$content,$_SESSION['user_id'],1);
if($comment && $comment->save()){
echo "Post submitted succesfully.";
}else{
$message = Comment::$comment_message;
}
}
}
The code without the JS is working as expected. What I'm trying to do is submit the comment without the page refreshing. Here is the JS code I tried but as it seems failed.
$(document).ready(function(){
$('.commentform').submit(function(event){
event.preventDefault();
var form = $(this);
var posturl = form.attr('action');
var comment = form.find('textarea[name="content"]').val();
//var comment = $(this).closest($('.comment_content'));
$.post(posturl, comment, function(data){
console.log(data);
});
});
});
What is going wrong? After pressing the submit button the page remains but the comment doesn't get submitted. (i can tell that by reloading the page)
Upvotes: 0
Views: 295
Reputation: 91734
The problem is that you are not posting a key - value pair but just the value:
var comment = form.find('textarea[name="content"]').val();
should be something like:
var comment = {'content': form.find('textarea[name="content"]').val()};
Apart from that you need to post all values as your php will fail if you don't so you are better of using something like:
var comment = form.serialize();
Edit: As you still have a problem, You need to console.log
all your javascript variables before you post; if the js is in another folder, the action / url is probably wrong.
Upvotes: 1