Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent redirect after form is submitted

I have an HTML form that submits an email with PHP, and when it submits, it redirects to that PHP page. Is there a way to prevent this redirect from happening? I built an animation with jQuery that I want to occur instead of redirecting. I tried return false;, but it wouldn't work. Here's my function:

$(function() {     $('.submit').click(function() {         $('#registerform').submit();         return false;     });  }); 

Here's the opening form tag:

<form id="registerform" action="submit.php" method="post"> 

And the submit button:

<input type="submit" value="SUBMIT" class="submit" /> 
like image 505
Robert Pessagno Avatar asked Oct 27 '10 23:10

Robert Pessagno


People also ask

How do I stop form from refreshing after submitting HTML?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

How does JavaScript prevent a form from being submitted?

Use the return value of the function to stop the execution of a form in JavaScript.

How do you prevent a form from clearing fields on submit?

You can use preventDefault method of the event object.


2 Answers

You should post it with ajax, this will stop it from changing the page, and you will still get the information back.

$(function() {     $('form').submit(function() {         $.ajax({             type: 'POST',             url: 'submit.php',             data: { username: $(this).name.value,                      password: $(this).password.value }         });         return false;     });  }) 

See Post documentation for JQuery

like image 57
Bruce Armstrong Avatar answered Sep 23 '22 18:09

Bruce Armstrong


Instead of return false, you could try event.preventDefault(); like this:

$(function() { $('#registerform').submit(function(event) {     event.preventDefault();     $(this).submit();     });  }); 
like image 44
bozdoz Avatar answered Sep 22 '22 18:09

bozdoz