Skip to content

Ajax form #65

Description

@josephlewisnz

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions