Skip to content
Grav 2.0 is officially stable. Read the announcement →
Forms & Blueprints

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 · 4265 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, 5 years ago
13 1427 5 months ago
Forms & Blueprints · by Hugo Oliveira, 6 months ago
0 219 6 months ago
Forms & Blueprints · by Flachy Joe, 7 months ago
9 314 7 months ago
Forms & Blueprints · by Augustus, 7 months ago
7 294 7 months ago
Forms & Blueprints · by Julien, 8 months ago
10 331 8 months ago