Support

Account

Home Forums Front-end Issues acf_form() and AJAX

Helping

acf_form() and AJAX

  • Hi

    I have been trying to call acf_form() in front end through AJAX. I have finally managed to get Edit to work flawlessly, but have some problems with inserting a new post. Whenever I insert a new post, whatever I enter will be stored in wp_option table and used as default for the next new post. Here’s portions of my code I thought would be relevant.

    JavaScript to get the form and submit it back:

    function newPost(contentType) {
        document.getElementById(contentType + "_holder").innerHTML = "<div class='ajaxloading'>&nbsp;</div>";
        jQuery(document).ready(function($) {
                    var data = {
                        action: 'new_post',
                        post_type: contentType,
                        security : MyAjax.security,
                    };
                    $.post(MyAjax.ajaxurl, data, function(response) {
                        document.getElementById(contentType + "_holder").innerHTML = response;
                        initACF(contentType);
                    });
                });
        return false;
    }
    
    function initACF(contentType) {
         $(document).trigger('acf/setup_fields', [
            $('#poststuff')
          ])
        $('.acf-form').on('submit', (event) => {
            event.preventDefault();
            
            var form_data = {'action' : 'acf/validate_save_post', 'post_type': contentType};
            jQuery('.acf-form :input').each(function() {
                form_data[jQuery(this).attr('name')] = jQuery(this).val();
            })
            
            form_data.action = 'save_my_data';
            $('html,body').css('cursor', 'wait');
            jQuery.post(MyAjax.ajaxurl, form_data).done(function(save_data) {
                $('html,body').css('cursor', 'default');
                getContent(contentType);
            })
        });
    }
    

    php code to call acf_form and send it back to the ajax request:

    function new_post_callback() {
        check_ajax_referer('my-special-string', 'security');
        switch ($_POST['post_type']) {
            case "contacts":
                $field_group = 80;
                break;
            case "vacations":
                $field_group = 103;
                break;
            case "messages":
                $field_group = 84;
                break;
            default:
                wp_die();
        }
        $settings = array(
            'id' => 'acf-form',
            'post_id' => 'new_post',
            'new_post' => array('post_type' => $_POST['post_type']),
            'return' => '',
            'field_groups'=>array($field_group),
            'html_before_fields' => '',
            'html_after_fields' => '',
            'submit_value' => __("Insert", 'acf'),
            'updated_message' => __("Post inserted", 'acf'),
            'label_placement' => 'top',
            'instruction_placement' => 'label',
            'honeypot' => true,
            'html_submit_button'	=> '<input type="submit" class="acf-button button button-primary button-large" value="%s" />',
            'kses'	=> false
    	);
        acf_form($settings);
        wp_die();
    }
    
    add_action('wp_ajax_new_post', 'new_post_callback');

    And here’s the code which saves new posts:

    function my_acf_save_post($post_id) {
    	if ($post_id !== 'new_post') {
    		return $post_id;
    	}
    	
    	$post = array(
    	            'post_status' => 'private',
    	            'post_type' => $_POST['post_type']);
    	switch ($_POST['post_type']) {
    	    case 'contacts':
    	        $fields = array('name'=>$_POST['fields'][NAME_FIELD], 'email'=>$_POST['fields'][EMAIL_FIELD]);
    	        break;
    	    case 'vacations':
    	        $fields = array('date_from'=>$_POST['fields'][DATE_FROM_FIELD], 'date_to'=>$_POST['fields'][DATE_TO_FIELD]);
    	        break;
    	    case 'messages':
    	        $fields = array('subject'=>$_POST['fields'][SUBJECT_FIELD], 'receipients'=>$_POST['fields'][RECEIPIENTS_FIELD], 'message'=>$_POST['fields'][MESSAGE_FIELD], 'release_in'=>$_POST[RELEASE_IN_FIELD]);
    	        break;
    	    default:
    	        return $post_id;
    	}
    	
    	$post_id = wp_insert_post($post);
    	foreach ($fields as $key => $value) {
    	    update_field($key, $value, $post_id);
    	}
    	
    	return $post_id;
    }

    Of interest is, I need to call this only for new posts, as edits work perfectly by simply using acf_form_head() as the ajax action.

    I would really appreciate any help. I tried to post this on wordpress.stackexchange.com but people there didn’t really think much of it and started down voting :'(

  • I have tracked this to line 201 of advanced-custom-fields/core/fields/_functions.php where it checks to see if the post id is not numeric and then writes store the values as default values. What I can’t understand is whether this is the expected behavior for ACF or not?

    My ACF version is 4.4.12, and my WP is 4.9.4

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘acf_form() and AJAX’ is closed to new replies.