Skip to content
Grav 2.1 is out: every page speaks Markdown. Read the announcement →

AJAX - how to hide a form after successful submission?

Solved by Oona O'Neil View solution

Started by Oona O'Neil 9 years ago · 1 replies · 4484 views
9 years ago

I'm trying to hide a front-end form after a successful submission - when the user have filled the form with correct data. Otherwise, I'd like both the form and an error message to be visible. My current solution hides the form in both cases. Could you help me to tweak it?

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

        // submit the form via Ajax
        $.ajax({
            url: newsletterForm.attr('action'),
            type: newsletterForm.attr('method'),
            dataType: 'html',
            data: newsletterForm.serialize(),
            success: function(result) {
                $('#newsletter-form-result').html(result);
                $('.newsletter_form--hide-js').hide();
                $('.newsletter__info-text').hide();
            }
        });
    });
});
9 years ago Solution

Got it working by adding if statement:

JS
success: function(result) {
                $('#newsletter-form-result').html(result);
                if ($('#newsletter-form-result div.alert.notices').hasClass('green')) {
                    $('.newsletter_form--hide-js').hide();
                    $('.newsletter__info-text').hide();
                }
            }

Suggested topics

Topic Participants Replies Views Activity
Forms & Blueprints · by Ton Haarmans, 6 years ago
13 2071 7 months ago
Forms & Blueprints · by Hugo Oliveira, 8 months ago
0 574 8 months ago
Forms & Blueprints · by Flachy Joe, 9 months ago
9 664 9 months ago
Forms & Blueprints · by Augustus, 9 months ago
7 715 9 months ago
Forms & Blueprints · by Julien, 10 months ago
10 700 10 months ago