Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ajax form #65

Open
josephlewisnz opened this issue Mar 17, 2021 · 0 comments
Open

Ajax form #65

josephlewisnz opened this issue Mar 17, 2021 · 0 comments
Labels

Comments

@josephlewisnz
Copy link

Hi there,

I am just trying to convert a form into an AJAX form.

I can seem to find a nice way to get this working if they do not "tick" the required Recaptcha field.

Basically, if the form fails in any way, then the entire form is returned (with validation messages), however, the Recaptcha never re-renders after this point.

I'm wondering If I cannot rely on the normal form flow and I should be relying on a custom submit endpoint and validate everything manually?

    public function SignUpForm() {     
        $fields = new FieldList(
            TextField::create('Name', 'Name'),
            EmailField::create('Email', 'Email'),
            TextField::create('District', "Tell us what district you're from")->addExtraClass('district')
        );

        $actions = new FieldList(
            FormAction::create('doSignUpForm', 'Sign up')
        );

        $validator = new RequiredFields([
            'Name', 
            'Email', 
            'District'
        ]);

        $form = new Form($this, 'SignUpForm', $fields, $actions, $validator);

        $form->addExtraClass('sign-up-form');
        $form->disableSecurityToken();
        $form->enableSpamProtection();

        return $form;
    }

 public function doSignUpForm($data, $form){
   //does not make it here if form validation does not pass eg recaptcha

   //db actions here and build response
      return $response;
}

JS

$(document).on('submit', '.sign-up-form', function(e) {
            e.preventDefault();
            var form = $('.sign-up-form');
            var data = $(form).serialize();
            
            $.ajax({
                method: 'POST',
                data: data,
                url: $(form).attr('action'), //home/SignUpForm
                success: function(response) {
                    if(response.message == 'Success'){
                       // success
                    } else{
                    //replace form holder with form html including validation messages
                        $('#homepage-SignUpForm').html(response);
                        
                    }
                    
                }
            });
        });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants