Skip to content
● Meet Grav Guard: keep every Grav site you run secure and up to date, all from one place. Free for up to 3 sites. Read more →

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 · 4739 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 TomW, 3 weeks ago
3 277 3 weeks ago
Forms & Blueprints · by Japhy, 1 month ago
2 526 1 month ago
Forms & Blueprints · by FrViPofm, 2 months ago
5 522 2 months ago
Forms & Blueprints · by Ton Haarmans, 6 years ago
13 2516 9 months ago
Forms & Blueprints · by Hugo Oliveira, 10 months ago
0 958 10 months ago