-2

I'm trying to hide a form after a correct submission. ATM, I have this code and it keeps the form and only displays success/error the message below the form. If errors appear, I'd like to keep the form, so the user can still provide the right details, but if it's a success I'd like to prevent them from double submission by hiding the form.

Here's my .js code:

$(document).ready(function() {
const form = $('.js-form-contact');
form.submit(function(e) {
    // prevent form submission
    e.preventDefault();

    // submit the form via Ajax
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        dataType: 'html',
        data: form.serialize()
   success: function(result) {
            // Inject the result in the HTML
            $('#form-result').html(result);
        }
});

});

I was thinking of creating an if statement and using the class of the div with the success message, but not sure what method to apply. Any suggestions welcome.

Here's my .html.twig file, where I injected the form:

<div id="{{ page.header.id }}">
    <div class="container">
        <h1>{{ page.header.header }}</h1>
        <div class="contact__form--hide-js">
        {% include "forms/form.html.twig" with {form: forms('contact_form')} %}
        </div>
        <div class="contact__form__bottom">
        </div>

        <div id="form-result"></div>
    </div>
</div>

Here's form-messages.html.twig file:

{% if form.message %}
    {% set message = form.inline_errors and form.messages ? "FORM.VALIDATION_FAIL"|t : form.message %}

    <div class="alert notices {{ form.message_color ?: 'green' }}"><p>{{ message|raw }}</p></div>
{% endif %}

Hope that helps.

  • I've found some ideas here: https://stackoverflow.com/questions/2830542/prevent-double-submission-of-forms-in-jquery – Oona O'Neil Nov 28 '17 at 09:16

1 Answers1

1

You can use .ajax() request instead of .submit(), read API doc for more info.

$.ajax({
  'url': url,
  'type': 'POST',
  'data': $('.contact__form--hide-js').serialize()
}).done( function(data){
   $('.contact__form--hide-js').hide();
}).fail(function(jqXHR, textStatus, errorThrown){
   console.log( errorThrown );
});

Or you can use .post() request,

$.post( "url_to_file")
.done(function() {
  alert( "success" );
})
.fail(function() {
  alert( "error" );
})
.always(function() {
  alert( "finished" );
});
Casper
  • 1,469
  • 10
  • 19