Support

Account

Home Forums General Issues Frontend form – post via ajax? Reply To: Frontend form – post via ajax?

  • Hey everyone,

    There’s actually a way to use one and single ajax request during a acf_form() front-end posting.

    You can take advantage of the acf/validate_save_post hook which is fired at the beginning of the acf_form() ajax validation request.

    You just have to trigger acf_get_validation_errors() with a wp_send_json_success return in order to keep the inherent ACF Form validation (required field, minimum/maximum etc…). Then, you must use new acf_form_front() to process the form in your ajax request, just like ACF Form does when it reloads the page after validation.

    Here is an exemple of the hook usage:

    
    add_action('acf/validate_save_post', 'hwk_ajax_acf_form_hook');
    function hwk_ajax_acf_form_hook(){
        if(!wp_doing_ajax() || !isset($_POST['_acf_post_id']) || !acf_verify_nonce('acf_form'))
            return;
            
        // Native ACF Form validation (required, minimum/maximum etc...)
        if($errors = acf_get_validation_errors())
            wp_send_json_success(array(
                'valid' 	=> 0,
                'errors' 	=> $errors,
            ));
        
        // acf_form() arguments are stocked in $_POST['_acf_form']
        if(!$form = $_POST['_acf_form'])
            return;
        
        // Decoding the form arguments via acf_decrypt().
        $form = json_decode(acf_decrypt($form), true);
            
        // Creating a 'proxy form' for the Legacy ACF Form fields saving
        // Setting 'return' to null to avoid built-in redirection
        $proxy = $form;
        $proxy['return'] = '';
    
        // Using native ACF Form submission method
        acf()->form_front = new acf_form_front();
        acf()->form_front->submit_form($proxy);
    
        wp_send_json_success(array(
            'valid' => 1,
            'data' 	=> 'Success!',
        ));
    }
    

    The javascript part use the acf.add_filter('validation_complete') filter. Remember to add preventDefault() on form submission to avoid the legacy acf_form() page reload.

    
    $('.acf-form.acf-form-ajax').on('submit', function(e){
        e.preventDefault();
    });
    

    If you’re interested about the whole process, I’ve written a full tutorial, including the creation of a Login, Register, Lost password & My Account forms with ACF Form, 100% in Ajax: https://hwk.fr/blog/acf-creer-un-formulaire-de-connexion-inscription-en-ajax-grace-acf-form

    It’s written in french, but the code is english-friendly 😉