0

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]

7
  • 1
    $('#button-form').click(function(event){ event.preventDefault(); ...... Commented Jul 29, 2020 at 19:53
  • still same problem, not submitting without page refresh Commented Jul 29, 2020 at 19:56
  • No @Junc it should not present the same problem .. take a look at w3schools.com/jquery/… Commented Jul 29, 2020 at 20:00
  • I triend the code you sent, but when i pressed the send butotn, did the same function as before. (not submitting without page refresh) Commented Jul 29, 2020 at 20:01
  • 1
    see @j4g0's updated answer it should solve your problem .. While I always prefer to use the form submit event instead of button click event for a form Commented Jul 29, 2020 at 20:04

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

14 Comments

I added the prevention event still not working. and the action="" i wan to be emtpy (i ran the query on the same page)
my bad, we should actually add the EventListener before trying to react to that event
You forgot to add event to function(event) :-)
don't think it is necessary in jQuery :D
$(document).ready(function(){ $('#form').on('submit', function (event) { event.preventDefault() .. this is the updated code, same problem
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.