Skip to content
● Grav 2.2 is out: 2x faster cold starts and 96% less memory on big sites. 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 · 4616 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 Japhy, 5 hours ago
0 12 5 hours ago
Forms & Blueprints · by FrViPofm, 3 weeks ago
5 274 3 weeks ago
Forms & Blueprints · by Ton Haarmans, 6 years ago
13 2265 8 months ago
Forms & Blueprints · by Hugo Oliveira, 9 months ago
0 729 9 months ago
Forms & Blueprints · by Flachy Joe, 10 months ago
9 810 10 months ago