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

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

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 · 4131 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 1138 4 months ago
Forms & Blueprints · by Hugo Oliveira, 5 months ago
0 61 5 months ago
Forms & Blueprints · by Flachy Joe, 6 months ago
9 135 6 months ago
Forms & Blueprints · by Augustus, 7 months ago
7 110 7 months ago
Forms & Blueprints · by Julien, 7 months ago
10 129 7 months ago