Stop form refreshing page on submit

Stop form refreshing page on submit

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
In particular I think the processForm() function at the bottom is ‘bad’.
HTML





JS
$(document).ready(function() {

// Add active class to inputs
$(“#prospects_form .boxsize”).focus(function() { $(this).addClass(“hasText”); });
$(“#form_validation .boxsize”).focus(function() { $(this).parent().addClass(“hasText”); });
// Remove active class from inputs (if empty)
$(“#prospects_form .boxsize”).blur(function() { if ( this.value === “”) { $(this).removeClass(“hasText”); } });
$(“#form_validation .boxsize”).blur(function() { if ( this.value === “”) { $(this).parent().removeClass(“hasText”); } });

///////////////////
// START VALIDATION
$(“#prospects_form”).ready(function() {

// DEFINE GLOBAL VARIABLES
var valName = $(‘#form_name’),
valEmail = $(“#form_email”),
valEmailFormat = /^(([^<>()[\]\\.,;:\s@\”]+(\.[^<>()[\]\\.,;:\s@\”]+)*)|(\”.+\”))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $(‘#form_message’),
valCaptcha = $(‘#form_captcha’),
valCaptchaCode = $(‘.form_captcha_code’);

// Generate captcha
function randomgen() {
var rannumber = “”;
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); } // Apply captcha to element valCaptchaCode.html(rannumber); } randomgen(); // CAPTCHA VALIDATION valCaptcha.blur(function() { function formCaptcha() { if ( valCaptcha.val() == valCaptchaCode.html() ) { // Incorrect valCaptcha.parent().addClass("invalid"); return false; } else { // Correct valCaptcha.parent().removeClass("invalid"); return true; } } formCaptcha(); }); // Remove invalid class from captcha if typing valCaptcha.keypress(function() { valCaptcha.parent().removeClass("invalid"); }); // EMAIL VALIDATION (BLUR) valEmail.blur(function() { function formEmail() { if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) { // Incorrect valEmail.addClass("invalid"); } else { // Correct valEmail.removeClass("invalid"); } } formEmail(); }); // Remove invalid class from email if typing valEmail.keypress(function() { valEmail.removeClass("invalid"); }); // VALIDATION ON SUBMIT $('#prospects_form').submit(function() { console.log('user hit send button'); // EMAIL VALIDATION (SUBMIT) function formEmailSubmit() { if (!valEmailFormat.test(valEmail.val())) { // Incorrect valEmail.addClass("invalid"); } else { // Correct valEmail.removeClass("invalid"); } } formEmailSubmit(); // Validate captcha function formCaptchaSubmit() { if( valCaptcha.val() === valCaptchaCode.html() ) { // Captcha is correct } else { // Captcha is incorrect valCaptcha.parent().addClass("invalid"); randomgen(); } } formCaptchaSubmit(); // If NAME field is empty function formNameSubmit() { if ( valName.val() === "" ) { // Name is empty valName.addClass("invalid"); } else { valName.removeClass("invalid"); } } formNameSubmit(); // If MESSAGE field is empty function formMessageSubmit() { if ( valMsg.val() === "" ) { // Name is empty valMsg.addClass("invalid"); } else { valMsg.removeClass("invalid"); } } formMessageSubmit(); // Submit form (if all good) function processForm() { if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) { $("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php"); $("#form_send").attr("type", "submit"); return true; } else if( !formEmailSubmit() ) { valEmail.addClass("invalid"); return false; } else if ( !formCaptchaSubmit() ) { valCaptcha.parent().addClass("invalid"); return false; } else if ( !formNameSubmit() ) { valName.addClass("invalid"); return false; } else if ( !formMessageSubmit() ) { valMsg.addClass("invalid"); return false; } else { return false; } } }); }); // END VALIDATION ///////////////// });

Solutions/Answers:

Solution 1:

You can prevent the form from submitting with

$("#prospects_form").submit(function(e) {
    e.preventDefault();
});

Of course, in the function, you can check for empty fields, and if anything doesn’t look right, e.preventDefault() will stop the submit.

Solution 2:

Replace button type to button:

<button type="button">My Cool Button</button>

Solution 3:

Add this onsubmit=”return false” code:

<form name="formname" onsubmit="return false">

That fixed it for me. It will still run the onClick function you specify

Solution 4:

You can use this code for form submission without a page refresh. I have done this in my project.

$(function () {
    $('#myFormName').on('submit',function (e) {

              $.ajax({
                type: 'post',
                url: 'myPageName.php',
                data: $('#myFormName').serialize(),
                success: function () {
                 alert("Email has been sent!");
                }
              });
          e.preventDefault();
        });
});

Solution 5:

This problem becomes more complex when you give the user 2 possibilities to submit the form:

  1. by clicking on an ad hoc button
  2. by hitting Enter key

In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.

And now comes the problem with IE (in any case version 11)
Remark:
This issue does not exist with Chrome nor with FireFox !

  • When you click the submit button the form is submitted once; fine.
  • When you hit Enter the form is submitted twice … and your servlet will be executed twice. If you don’t have PRG (post redirect get) architecture serverside the result might be unexpected.

Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks.
This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)

The source code HTML & js are in the snippet. The principle is described there.
Warning:

You can’t test it in the snippet because the post action is not
defined and hitting Enter key might interfer with stackoverflow.

If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.

/*
 * inForm points to the form
 */
var inForm = document.getElementById('idGetUserFrm');
/*
 * IE submits the form twice
 * To avoid this the boolean isSumbitted is:
 *  1) initialized to false when the form is displayed 4 the first time
 * Remark: it is not the same event as "body load"
 */
var isSumbitted = false;

function checkEnter(e) {
  if (e && e.keyCode == 13) {
    inForm.submit();
    /*
      * 2) set to true after the form submission was invoked
      */
    isSumbitted = true;
  }
}
function onSubmit () {
  if (isSumbitted) {
    /*
    * 3) reset to false after the form submission executed
    */
    isSumbitted = false;
    return false;
  }
}
<!DOCTYPE html>
<html>
<body>

<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
   First name:<br>
   <input type="text" name="firstname" value="Mickey">
   <input type="submit" value="Submit">
</form>

</body>
</html>

Solution 6:

Most people would prevent the form from submitting by calling the event.preventDefault() function.

Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();

katsh‘s answer is the same, just easier to digest.

(By the way, I’m new to stackoverflow, give me guidance please. )