Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Preventing the "double submit" problem in Ajax form

I have website contact form that, when submitted, sometimes takes a few second to send.

The user, usually because they’re impatient, clicks again. This results in the form being sent multiple times to the host.

To prevent this, I’ve tried implementing something along these lines, but thinking there’s something cleaner and better:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$.fn.click1 = function(fn) {  
  $(this).data('clicked', false);  
  $(this).click(function(o) {  
    if ($(this).data('clicked')) return false;  
    $(this).data('clicked', true);  
    fn(o);  
    return false;  
  });  
};  
$(function() {

  // get the form
  var form = $('#modal-contact-form');

  // get the messages element
  var formMessages = $('#modal-contact-form-responses');

  // set up event listener for contact form
  $(form).submit(function(e) {
    // disable html submit button
    e.preventDefault();

    // serialize form data
    var formData = $(form).serialize();

    // submit form using AJAX
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
      })
      .done(function(response) {
        // make sure formMessages element has 'success' class
        $(formMessages).removeClass('error');
        $(formMessages).addClass('success');

        // set message text
        $(formMessages).text('Your message has been sent. Thank you!');

        // clear form
        $('input, textarea').val('');
        $("#modal-contact-form-message").trigger('change');
      })
      .fail(function(data) {
        // make sure formMessages element has 'error' class
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');

        // set the message text
        $(formMessages).text('Input error. Please review and re-submit.');
      });

  });

});

// text area character counter
// disables submit button when < 0
(function($) {

  $.fn.charCount = function(submit, options) {

    this.submit = submit;

    // default configuration properties
    var defaults = {
      allowed: 1250,
      warning: 150,
      css: 'counter',
      counterElement: 'span',
      cssWarning: 'warning',
      cssExceeded: 'exceeded',
      counterText: ''
    };

    var options = $.extend(defaults, options);

    function calculate(obj, submit) {

      submit.attr("disabled", "disabled");

      var count = $(obj).val().length;
      var available = options.allowed - count;
      if (available <= options.warning && available >= 0) {
        $(obj).next().addClass(options.cssWarning);
      } else {
        $(obj).next().removeClass(options.cssWarning);
      }
      if (available < 0) {
        $(obj).next().addClass(options.cssExceeded);
      } else {
        $(obj).next().removeClass(options.cssExceeded);
        submit.removeAttr("disabled");
      }

      $(obj).next().html(options.counterText + available);
    };

    this.each(function() {
      $(this).after('<' + options.counterElement + ' class="' + options.css + '">' + options.counterText + '</' + options.counterElement + '>');

      calculate(this, submit);

      $(this).keyup(function() {
        calculate(this, submit)
      });
      $(this).change(function() {
        calculate(this, submit)
      });
    });

  };

})(jQuery);

$(document).ready(function() {
  $("#modal-contact-form-message").charCount($("#modal-contact-form-submit"));
});
<form action="process_contact_form/" method="post" id="modal-contact-form">

  <div>
    <label for="modal-contact-form-name">Name</label>
    <input type="text" name="name_cform" id="modal-contact-form-name">
  </div>

  <div>
    <label for="modal-contact-form-email">E-mail</label>
    <input type="email" name="email_cform" id="modal-contact-form-email">
  </div>

  <div id="subject-line">
    <label for="modal-contact-form-subject">Subject</label>
    <input type="text" name="subject_cform" id="modal-contact-form-subject">
  </div>

  <div id="counter-container">
    <label for="modal-contact-form-message">Message</label>
    <textarea name="message_cform" id="modal-contact-form-message"></textarea>
  </div>

  <input type="hidden" name="formtarget_cform" value="modal" id="modal-contact-form-hidden">

  <button type="submit" name="submit_cform" id="modal-contact-form-submit">Send Message</button>

  <p id="modal-contact-form-responses"></p>

</form>

>Solution :

First, you can disable the submit button when the form is submitted. This prevent any unnecessary further form submission.
Then remove the disabled attribute once the ajax request is completed via jqXHR.always() method.

You can also change the button’s text to Sending Message... for the user to know that the form is submitting.

Kindly change this part <!-- AJAX form messaging --> to this

$(function() {

    // get the form
    var form = $('#modal-contact-form');

    // get the messages element
    var formMessages = $('#modal-contact-form-responses');

    // get the submit button
    var submitButton = $("#modal-contact-form-submit");

    // set up event listener for contact form
    $(form).submit(function(e) {
        // disable html submit button
        e.preventDefault();

        // serialize form data
        var formData = $(form).serialize();

        // disable submit button to prevent unnecessary submission
        submitButton.attr('disabled', 'disabled');
        submitButton.text('Sending Message...'); // this help the user to know that the form is sending

        // submit form using AJAX
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            // make sure formMessages element has 'success' class
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // set message text
            $(formMessages).text('Your message has been sent. Thank you!');

            // clear form
            $('input, textarea').val('');
            $("#modal-contact-form-message").trigger('change');
        })
        .fail(function(data) {
            // make sure formMessages element has 'error' class
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // set the message text
            $(formMessages).text('Input error. Please review and re-submit.');
        }).always(function(data) { // this will always fire even if the request fails
            submitButton.removeAttr('disabled');
            submitButton.text('Send Message');
        });

    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading