skip to Main Content

I have the form like this:

<form method="POST" action="bubble2.php" id="bubbleName">
    <input id="myInput" name="namehere" type="text">
    <input name="submit" type="submit">  
</form>

And the script which prevents redirecting or reloading the page after submit:

<script>
$(document).ready(function(){
   $('form').submit(function(e){
    e.preventDefault();

        $.ajax({
            type: 'POST',
            url: 'bubble.php',
            data: $('form').serialize(),
            success: function(data) {

                 $('#bubbleName')[0].reset();

            }
        });

   });
});
</script>

What I need is the script to run only once after submit.

2

Answers


  1. You can use one for that:

    <script>
    $(document).ready(function(){
       $('form').one('submit', function(e){
        e.preventDefault();
    
            $.ajax({
                type: 'POST',
                url: 'bubble.php',
                data: $('form').serialize(),
                success: function(data) {
    
                     $('#bubbleName')[0].reset();
    
                }
            });
    
       });
    });
    </script>
    
    Login or Signup to reply.
  2. first, add class name or id to the submit button and then add EventListener

     <form method="POST" action="bubble2.php" id="bubbleName">
       <input id="myInput" name="namehere" type="text">
       <input name="submit" type="submit" class="btn">  
     </form>
    
    document.querySelector(".btn").addEventListener("click",function(){
    
      //enter your code here
    
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search