Ajax Form - Submitting from all Forms on same page

1k Views Asked by At

I have a page with two forms on the same page. The two forms is displayed based on viewport (responsive design/media queries css).

On the page I am using bootstrapvalidator in order to validate the fields, and Ajax in order to submit the forms without browser reload. Because of the bootstrapvalidator, the Ajax code looks like this - a code that targets ALL forms:

  $('form').on('success.form.bv', function(e) {
    var thisForm = $(this);

    //Prevent the default form action
    e.preventDefault();

    //Hide the form
    $(this).fadeOut(function() {
      //Display the "loading" message
      $(".loading").fadeIn(function() {
        //Post the form to the send script
        $.ajax({
          type: 'POST',
          url: thisForm.attr("action"),
          data: thisForm.serialize(),
          //Wait for a successful response
          success: function(data) {
            //Hide the "loading" message
            $(".loading").fadeOut(function() {
              //Display the "success" message
              $(".success").text(data).fadeIn();
            });
          }
        }); 
      });
    });

The problem with this code, as it seems, is the fact that the code will send two mails, one for the visible form, and one for the hidden mobile/tab form - the success msg will actually be displayed for both forms (when I resize the browser to target both desktop and mob/tablet, I can see the success msg for both forms). First I thought is was because of something wrong with the e.preventDefault(); and then I thought the problem was caused by name conflicts on the submit name/id of the submit button. But now I am pretty sure it has to do with the existence of the two forms on the same page - because the only way I manage to fix this whole problem right now is by completely remove one of the forms, and that's really not a solution!

My forms look like this with different form id (html5form/html5formmob) and input submit id (mob/desk):

    <form id="html5Form" method="post" action='mail/mail.php'
          class="form-horizontal"
          data-bv-message="This value is not valid"
          data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
          data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
          data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">    

              <div class="form-group">
                      <label>Name</label>
                      <input class="form-control" type="text" name="name" id="name"
                             data-bv-message="The username is not valid"
                             required data-bv-notempty-message="Please give a name"/>
              </div>

              <div class="form-group">
                  <label>Mail</label>
                      <input class="form-control" name="email" id="email" type="email" required data-bv-emailaddress-message="No valid email"  />
              </div>

              <div class="form-group">
                <label>Msg</label>
                <textarea class="form-control" name="message" id="message" rows="7" required 
                data-bv-notempty-message="No empty msg"></textarea>
              </div>  

                <input type="submit" id="mob" value="Send"/>
            </form>
<div class="loading">
        Sending msg...
  </div>
  <div class="success">
  </div>

So my question, is there a way to disable/enable the entire form using CSS or JS? ..and could this be a solution, or do you have other suggestions?

2

There are 2 best solutions below

9
On

Try to change your JS part into this:

$('form').on('success.form.bv', function(e) {
    var thisForm = $(this), parent = thisForm.parent();

    //Prevent the default form action
    e.preventDefault();

    if (thisForm.is(':visible')) {
        //Hide the form
        thisForm.fadeOut(function() {
        //Display the "loading" message
        $(".loading", parent).fadeIn(function() {
            //Post the form to the send script
            $.ajax({
                type: 'POST',
                url: thisForm.attr("action"),
                data: thisForm.serialize(),
                //Wait for a successful response
                success: function(data) {
                    //Hide the "loading" message
                    $(".loading", parent).fadeOut(function() {
                        //Display the "success" message
                        $(".success", parent).text(data).fadeIn();
                    });
                }
            }); 
        });
    }
});

Will work dynamicly, so even when you switch forms by resizing your browser.

3
On

Try the following approach:

$('form').on('success.form.bv', function(e) {
var thisForm = $(this);

//Prevent the default form action
e.preventDefault();

if (getComputedStyle(thisForm[0], null).display != "none" )
{
    //Hide the form
    $(this).fadeOut(function() {
      //Display the "loading" message
      $(".loading").fadeIn(function() {
        //Post the form to the send script
        $.ajax({
          type: 'POST',
          url: thisForm.attr("action"),
          data: thisForm.serialize(),
          //Wait for a successful response
          success: function(data) {
            //Hide the "loading" message
            $(".loading").fadeOut(function() {
              //Display the "success" message
              $(".success").text(data).fadeIn();
            });
          }
        }); 
      });
    });
}
});

But you can also validate each form by itself:

  $('#html5Form')
    .formValidation({
        ... options ...
    })
    .on('success.form.fv', function(e) { ... ajax call ...} );

Or even better. wrap the ajax call in a function

function callAjax(form)
{
      form.fadeOut(function() {
      //Display the "loading" message
      $(".loading").fadeIn(function() {
        //Post the form to the send script
        $.ajax({
          type: 'POST',
          url: form.attr("action"),
          data: form.serialize(),
          //Wait for a successful response
          success: function(data) {
            //Hide the "loading" message
            $(".loading").fadeOut(function() {
              //Display the "success" message
              $(".success").text(data).fadeIn();
            });
          }
        }); 
      });
    });
}


  $('#html5Form')
    .formValidation({
        ... options ...
    })
    .on('success.form.fv', callAjax.bind(null, $(this)) );

  $('#html5formmob')
    .formValidation({
        ... options ...
    })
    .on('success.form.fv', callAjax.bind(null, $(this)) );