2

I'm using Javascript to validate a form. If the validation script does not find an error in the form, then the ajax submit code should run, but it isn't. I'm not sure why. If I put the submit code into its own script and remove the validation, the form submits just fine. I should also note that if you put a console.log("Success") before and after $("#foo").submit(function(event) {, only the first console log can be seen. So it seems that the submit function isn't firing for some reason.

<form id="foo" method="post" name="nomForm" action="nominate-test.html#thankyou" onsubmit="return validateForm()">

  <div class="page1">
    <label class="row">
      <h2 class="headline">Your name</h2>
      <input placeholder="e.g. John Smith" type="text" name="name" id="name" tabindex="1" autofocus>
      <span id="nameError" class="error headline"></span>
    </label>

    <label class="row email">
      <h2 class="headline">Your email address</h2>
      <input placeholder="[email protected]" type="text" name="email" id="email" tabindex="2">
      <span id="emailError" class="error headline"></span>
    </label>

    <label class="row">
      <h2 class="headline">Company name</h2>
      <input placeholder="e.g. Roford" type="text" name="company" id="company" tabindex="3">
      <span id="companyError" class="error headline"></span>
    </label>
    <div class="next">
      <button type="button" id="moveup">Next page</button><i class="icon-down-open"></i></div>
  </div>

  <div class="page2">
    <label class="row reason">
      <h2 class="headline">Reason for nomination</h2>
      <textarea id="textarea" rows="6" cols="25" maxlength="1000" name="message" id="message" placeholder="A brief evidence based summary"></textarea>
      <span id="messageError" class="error headline"></span>
      <div id="text-area-wrap">
        <div id="textarea_feedback"></div>
      </div>
    </label>

    <div class="row button-wrap">
      <div class="column small-12">
        <input class="button" name="submit" type="submit" id="contact-submit" value="Submit">
      </div>
    </div>
    <div class="prev">
      <button type="button" id="movedown">Previous page</button><i class="icon-up-open"></i></div>
  </div>

</form>


function validateForm() {
  var name = document.nomForm.name.value;
  var email = document.nomForm.email.value;
  var company = document.nomForm.company.value;
  var message = document.nomForm.message.value;
  var errorCount = 0;

  if (name == "") {
    document.getElementById('nameError').innerHTML = "Please enter your name";
    errorCount++;
  } else {
    var specCharNum = "~`!#$%^&*+=[]\\\';,/{}|\":<>?1234567890";
    for (var i = 0; i < name.length; i++) {
      if (specCharNum.indexOf(name.charAt(i)) != -1) {
        document.getElementById('nameError').innerHTML = "Please enter a valid name";
        errorCount++;
      }
    }
  }

  if (email == "") {
    document.getElementById('emailError').innerHTML = "Please enter your email address";
    errorCount++;
  } else {
    var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 > email.length) {
      document.getElementById('emailError').innerHTML = "Please enter a valid email address";
      errorCount++;
    }
  }

  if (company == "") {
    document.getElementById('companyError').innerHTML = "Please enter a company name";
    errorCount++;
  } else {
    var specChar = "~`!#$%^&*+=[]\\\';,/{}|\":<>?";
    for (var i = 0; i < name.length; i++) {
      if (specChar.indexOf(name.charAt(i)) != -1) {
        document.getElementById('companyError').innerHTML = "Please enter a valid company name";
        errorCount++;
      }
    }
  }

  if (message == "") {
    document.getElementById('messageError').innerHTML = "Please enter a reason";
    errorCount++;
  } else {
    if (message.length > 1000) {
      document.getElementById('messageError').innerHTML = "You have exceeded the character limit";
      errorCount++;
    }
  }

  if (errorCount > 0) {
    return false;
  } else {
    // Variable to hold request
    var request;

    // Bind to the submit event of our form
    $("#foo").submit(function(event) {

      // Abort any pending request
      if (request) {
        request.abort();
      }
      // setup some local variables
      var $form = $(this);

      // Let's select and cache all the fields
      var $inputs = $form.find("input, select, button, textarea");

      // Serialize the data in the form
      var serializedData = $form.serialize();

      // Let's disable the inputs for the duration of the Ajax request.
      // Elements are disabled AFTER the form data has been serialized.
      // Disabled form elements will not be serialized.
      $inputs.prop("disabled", true);

      // Fire off the request to /form.php
      request = $.ajax({
        url: "https://script.google.com/macros/s/AKfycbwpTdztz-kSw8Ld1o0yly6BD-2cvJglpq2gkKioMjGoWDMO_HE/exec",
        type: "post",
        data: serializedData
      });

      // Callback handler that will be called on success
      request.done(function(response, textStatus, jqXHR) {
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
      });

      // Callback handler that will be called on failure
      request.fail(function(jqXHR, textStatus, errorThrown) {
        // Log the error to the console
        console.error(
          "The following error occurred: " +
          textStatus, errorThrown
        );
      });

      // Callback handler that will be called regardless
      // if the request failed or succeeded
      request.always(function() {
        // Reenable the inputs
        $inputs.prop("disabled", false);
      });

      // Prevent default posting of form
      event.preventDefault();
    });
    return true;
  }
}

1 Answer 1

2

First remove onsubmit event from your form like this:

<form id="foo" method="post" name="nomForm" action="nominate-test.html#thankyou">

And use following javascript code:

function validateForm() {
  var name = document.nomForm.name.value;
  var email = document.nomForm.email.value;
  var company = document.nomForm.company.value;
  var message = document.nomForm.message.value;
  var errorCount = 0;

  if (name == "") {
    document.getElementById('nameError').innerHTML = "Please enter your name";
    errorCount++;
  } else {
    var specCharNum = "~`!#$%^&*+=[]\\\';,/{}|\":<>?1234567890";
    for (var i = 0; i < name.length; i++) {
      if (specCharNum.indexOf(name.charAt(i)) != -1) {
        document.getElementById('nameError').innerHTML = "Please enter a valid name";
        errorCount++;
      }
    }
  }

  if (email == "") {
    document.getElementById('emailError').innerHTML = "Please enter your email address";
    errorCount++;
  } else {
    var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 > email.length) {
      document.getElementById('emailError').innerHTML = "Please enter a valid email address";
      errorCount++;
    }
  }

  if (company == "") {
    document.getElementById('companyError').innerHTML = "Please enter a company name";
    errorCount++;
  } else {
    var specChar = "~`!#$%^&*+=[]\\\';,/{}|\":<>?";
    for (var i = 0; i < name.length; i++) {
      if (specChar.indexOf(name.charAt(i)) != -1) {
        document.getElementById('companyError').innerHTML = "Please enter a valid company name";
        errorCount++;
      }
    }
  }

  if (message == "") {
    document.getElementById('messageError').innerHTML = "Please enter a reason";
    errorCount++;
  } else {
    if (message.length > 1000) {
      document.getElementById('messageError').innerHTML = "You have exceeded the character limit";
      errorCount++;
    }
  }

  return errorCount;
}

$("#foo").submit(function(event) {

  var request;

  if ( validateForm() !== 0 ) {
    return false;
  }

  // Abort any pending request
  if (request) {
    request.abort();
  }
  // setup some local variables
  var $form = $(this);

  // Let's select and cache all the fields
  var $inputs = $form.find("input, select, button, textarea");

  // Serialize the data in the form
  var serializedData = $form.serialize();

  // Let's disable the inputs for the duration of the Ajax request.
  // Elements are disabled AFTER the form data has been serialized.
  // Disabled form elements will not be serialized.
  $inputs.prop("disabled", true);

  // Fire off the request to /form.php
  request = $.ajax({
    url: "https://script.google.com/macros/s/AKfycbwpTdztz-kSw8Ld1o0yly6BD-2cvJglpq2gkKioMjGoWDMO_HE/exec",
    type: "post",
    data: serializedData
  });

  // Callback handler that will be called on success
  request.done(function(response, textStatus, jqXHR) {
    // Log a message to the console
    console.log("Hooray, it worked!");
    console.log(response);
    console.log(textStatus);
    console.log(jqXHR);
    window.location = "nominate-test.html#thankyou";
  });

  // Callback handler that will be called on failure
  request.fail(function(jqXHR, textStatus, errorThrown) {
    // Log the error to the console
    console.error(
      "The following error occurred: " +
      textStatus, errorThrown
    );
  });

  // Callback handler that will be called regardless
  // if the request failed or succeeded
  request.always(function() {
    // Reenable the inputs
    $inputs.prop("disabled", false);
  });

  // Prevent default posting of form
  event.preventDefault();
});

It prevent from reloading page, then execute your ajax code. after run ajax, redirect user to thank you page with javascript.

Sign up to request clarification or add additional context in comments.

5 Comments

I changed the code as suggested, and the form does submit, but it submits even if the form isn't filled in correctly. It seems to bypass the validation.
This means you can send an empty form?
Yes, that's correct. An empty form or partially filled in form can be sent.
That's done it! Thanks a lot, I'll accept your answer. Would you be able to explain what you did?
When you submit a form in your code, after checking validation of inputs, you set a submit event for form now! in other words user have to twice click and submit form to send ajax data. by seprating validation and submit, you can check validation in first of submit event. hope useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.