UndefinedOffset / silverstripe-nocaptcha

A spam protector and form field using Google's reCAPTCHA v2 or optionally a foundation v3 implementation
BSD 3-Clause "New" or "Revised" License
31 stars 37 forks source link

Ajax form #65

Open josephlewisnz opened 3 years ago

josephlewisnz commented 3 years ago

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);

                    }

                }
            });
        });