Reputation: 21
Its very common question all over the internet but I don't know how to fix this problem. I have a comment system, where users can post comments. The problem is when someone posts comment on the 10th post of the page, by submitting the form they redirect to the top of the page, which i don't want. I want the comment to be sent successfully and the user must be on the same post. I hope i can understand you all experienced developers.
HTML FORM
<form id="form" action="" method="post">
<div class="input-group mb-3">
<img class="p-1 m-0" src="images/" width="35" height="35" alt="">
<input name="post_comment" id="add_comments" type="text" autofocus class="form-control pl-3 pr-3" placeholder="type somethign" aria-label="Recipient's username" aria-describedby="button-form">
<div class="input-group-append">
<button class="btn btn-secondary" type="submit" name="submit_comment" id="button-form">Add Comment</button>
</div>
</div>
</form>
JavaScript code:
<script>
$(document).ready(function(){
$('#button-form').click(function(){
var add_comments = $('#add_comments').val();
if(add_comments == '')
{
$('#error_msg').html("Comments blank!");
}
else
{
$('#error_msg').html('');
$.ajax({
url:"index.php",
method:'post',
data:{add_comments:add_comments},
success:function(data){
$("form").trigger("reset");
$('#succ_msg').fadeIn().html(data);
setTimeout(function(){
$('#success_message').fadeOut("Slow");
}, 2000);
}
});
}
});
});
</script>
PHP Query:
if(isset($_POST['submit_comment'.$ansRow['id']])){
$comments = $_POST['post_comment'.$ansRow['id']];
if(empty($comments)){
$cError = "Wrote nothing in comments!";
}else{
$comments = mysqli_real_escape_string($con,$_POST['post_comment'.$ansRow['id']]);
$cQuery = "INSERT INTO `qa-comments` (posted_at,updated_at,user_id,answer_id,question_id,comments_text)
VALUES
(now(),now(),'".$_SESSION['id']."','$ansId','$qId','$comments')";
if(mysqli_query($con,$cQuery)){
// header('refresh:0s');
}else{
$cError = "Something went wrong!";
// printf("Errormessage: %s\n", mysqli_error($con));
}
}
}
console erros.[![enter image description here][1]][1]
Upvotes: 0
Views: 89
Reputation: 198
You do not currently prevent the form from executing it's default behavior. When you click the button of type="submit" the form get's sent to the page specified in <form action="some_url"></form>
or to the same page, if that is empty
$(document).ready(function(){
$('#form').on('submit', function(){
event.preventDefault()
var add_comments = $('#add_comments').val();
if(add_comments == '')
{
$('#error_msg').html("Comments blank!");
}
else
{
$('#error_msg').html('');
$.ajax({
url:"index.php",
method:'post',
data:{add_comments:add_comments},
success:function(data){
$("form").trigger("reset");
$('#succ_msg').fadeIn().html(data);
setTimeout(function(){
$('#success_message').fadeOut("Slow");
}, 2000);
}
});
}
});
});
This will prevent the reloading of the page and execute your javascript instead
Upvotes: 1