简体   繁体   中英

Stop HTML form from disappearing after AJAX call

I am trying to make a comment system that has a basic validation in which the reply cannot be blank (0 characters).

When a user hits the reply button, the system will respond with an AJAX call to display a form (Textarea). When the user submits the form and the textarea is empty, an error message will appear beneath the form. My problem is that the form disappears immediately after the user submits the form and does not allow me to display an error message.

How do I stop the HTML form from disappearing until all validation succeeds?

index.php:

<script>
  $(document).ready(function(){
    $(".replyText").click(function(){
      $.ajax({
        type: "GET",
        url: "reply_ajax.php",
        async: false,
        success: function(text){
        response = text;        
        }
      });
      $(this).after(response);
    });
  });
</script>

reply_ajax.php:

<div class="replydiv">
    <textarea rows='4' cols='50' form='replyform' name='reply'>

    </textarea>
    <form id='replyform' method='post'>
            <input type='submit' name='submit' class='submit'>      
            <input type='submit' name='cancel' value='Cancel'>
    </form> 
</div>   
<script>
    $(function(){
            $(".submit").click(function(){
                    if($(this).closest('textarea').val() == "")
                            $(".comments").append("Please enter a reply!");                         
            });
    });

</script>

You could use e.preventDefault() to prevent postback like:

$(function(){
            $(".submit").click(function(e){
                    if($(this).closest('textarea').val() == ""){
                            $(".comments").append("Please enter a reply!");  
                            e.preventDefault()}                       
            });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM