Support

Account

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

  • Thanks everyone for posting their snippets, I thought I would share my compendium version of this just to bring it together as of Jan 2020 for other people looking to do something similar.

    I can’t dedicate a million hours to solving everyone’s issues in the future but hopefully this will be useful.

    My scenario was that I wanted to have a modal pop up on a button, load in an acf_form using a wordpress ajax request, and then submit it back via ajax before showing a success modal and letting the user return to the page.

    I have used jquery-modal for the modal library. Installed via npm install jquery-modal then enqueued the scripts/styles using normal wordpress features.

    I have used this tutorial for figuring out how to do ajax requests – https://benmarshall.me/wordpress-ajax-frontend-backend/

    The template that my WordPress ajax call returns is an acf_form() call:

    acf_form(array(
    	'post_id' => 'new_post',
    	'post_title' => true,
    	'new_post' => array(
    		'post_type' => 'yourposttypehere',
    		'post_status' => 'publish'
    	),
    	'form' => true,
    	'submit_value' => __("Add your post-type", 'textdomain'),
    ));
    

    I have a button to trigger it:

    
    	<a class="woocommerce-Button button js-addposttype-button" href="#">
    		<?php esc_html_e('Add post-type', 'textdomain'); ?>
    	</a>
    

    And this monster of JS:

    
        function setupAddPostTypeAJAX() {
            $('.js-addposttype-button').on('click', function (e) {
                e.preventDefault();
    
                this.blur(); // Manually remove focus from clicked link.
    
                var data = {
                    action: 'get_posttype_add_form',
                    security: myPostTypeAjax.security,
                };
    
                $.post(myPostTypeAjax.ajaxurl, data, function (response) {
                    // cant use jquery .wrap() here as it doesnt return the wrapped string
                    response = "<div class='modal'>" + response + "</div>";
                    var modalContent = $(response).appendTo('body');
                    acf.do_action('append', modalContent);
    
                    var $form = modalContent.find(".acf-form");
    
                    $form.on('submit', function (event) {
                        event.preventDefault();
                    });
    
                    modalContent.modal();
    
                    $form.find('.acf-form-submit .acf-button').on('click', function () {
                        args = {
                            form: $form,
                            reset: true,
                            success: function ($form) {
                                // Fix for Safari Webkit – empty file inputs kill the browser
                                // https://stackoverflow.com/a/49827426/586823
                                let $fileInputs = $('input[type="file"]:not([disabled])', $form)
                                $fileInputs.each(function (i, input) {
                                    if (input.files.length > 0) {
                                        return;
                                    }
                                    $(input).prop('disabled', true);
                                })
    
                                var formData = new FormData($form[0]);
    
                                // Re-enable empty file $fileInputs
                                $fileInputs.prop('disabled', false);
    
                                acf.lockForm($form);
    
                                $.ajax({
                                    url: window.location.href,
                                    method: 'post',
                                    data: formData,
                                    cache: false,
                                    processData: false,
                                    contentType: false
                                }).done(response => {
                                    acf.unlockForm($form);
                                    // show new modal saying posttype added
                                    var modalSuccessMessage = '<div class="modal">Your posttype has been added.</div>';
                                    $(modalSuccessMessage).appendTo('body').modal();
                                    
                                    // could also fire off a wordpress ajax here to update the underlying page data
                                    // if you are display a list of some kind of posttype and adding to it with this
                                });
                            }
                        }
    
                        acf.validateForm(args);
                    });
                });
            });
        }
    

    Its a combination of the various snippets that I’ve found throughout these forums so MASSIVE thanks to the people that have done the work on this before me. It would have been so many more hours of work without your helpful posts. I’m really grateful.

    As I understand it, this will support file uploads in your form of you have file fields. If you do then check the official acf_form page docs as there is an extra thing you will need to do for the wp uploader.

    Good luck everyone!