Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent form redirect OR refresh on submit?

I've searched through a bunch of pages, but can't find my problem, so I had to make a post.

I have a form that has a submit button, and when submitted I want it to NOT refresh OR redirect. I just want jQuery to perform a function.

Here's the form:

<form id="contactForm">     <fieldset>         <label for="Name">Name</label>         <input id="contactName" type="text" />     </fieldset>      <fieldset>         <label for="Email">Email</label>         <input id="contactEmail" type="text" />     </fieldset>      <fieldset class="noHeight">         <textarea id="contactMessage" cols="20"></textarea>         <input id="contactSend" class="submit" type="submit" onclick="sendContactForm()" />     </fieldset> </form>         <small id="messageSent">Your message has been sent.</small> 

And here is the jQuery:

function sendContactForm(){     $("#messageSent").slideDown("slow");     setTimeout('$("#messageSent").slideUp();$("#contactForm").slideUp("slow")', 2000); } 

I've tried with and without an action element on the form, but don't know what I'm doing wrong. What has annoyed me more is that I have an example that does it perfectly: Example Page

If you want to see my problem live, goto stormink.net (my site) and check out the sidebar where it says "Send me and email" and "RSS Subscription". Both are forms that I'm trying to get this to work on.

like image 393
Ian Storm Taylor Avatar asked Aug 12 '09 01:08

Ian Storm Taylor


People also ask

How do I stop confirmation resubmission on refresh?

You can prevent form resubmission via a session variable. Yes we can use microtime() as well as time() also instead of rand() , whatever function or variable that gives different value we can use it. BUT make sure that you set that value to SESSION variable.

How do I stop form submit from refreshing page in PHP?

One way to stop page resubmission on page refresh is to unset the form data after it is submitted so that the variable storing form data becomes empty and wrap up your form processing block of codes to check if the form is empty.

How do I stop a form resubmission when a page is refreshed in asp net?

As you probably know, ASP.NET Web Forms send POST requests back to the server and then re-render the Page in the same request. This is why we see the form re-submission message when we click "reload". To avoid this issue, we should employ the post-then-redirect pattern used by many web applications.


1 Answers

Just handle the form submission on the submit event, and return false:

$('#contactForm').submit(function () {  sendContactForm();  return false; }); 

You don't need any more the onclick event on the submit button:

<input class="submit" type="submit" value="Send" /> 
like image 200
Christian C. Salvadó Avatar answered Oct 09 '22 22:10

Christian C. Salvadó