Support

Account

Home Forums Backend Issues (wp-admin) Pass data to javascript function on acf/save_post

Helping

Pass data to javascript function on acf/save_post

  • Hi there,

    I’m breaking my head over a problem I can’t seem to grasp…
    What I would like to do is the following:

    I have several acf fields (on pages and in options) in my site that I watch with the acf/save_post hook:

    add_action('acf/save_post', array('InteractiveComponent', 'acfSavePost'), 10, 3);

    class InteractiveComponent {
    
    	public static function acfSavePost($post_id) {
    		$screen  = get_current_screen();
    		$options = array(
    			'acf-options-colors',
    			'acf-options-icons',
    			'acf-options-fonts',
    			'acf-options-remaining-variables',
    			'acf-options-custom-scss'
    		);
    
    		foreach ($options as $option) {
    			if (strpos($screen->id, $option) == true) {
    				self::processData();
    			}
    		}
    	}
    }

    The new values get passed to a function to process an output.
    This output should be send to a javascript function that’s already enqueued in the backend.

    public static function processData() {
    	$data = someFunction();
    	if ($data) {
    		// send $data to my javascript function
    		// <script>testReceiveData(<?= $data; ?>);</script>
    		echo '<script>testReceiveData('. json_encode($data). ')</script>';
    	}
    }

    My javascript:

    (function($) {
    	function testReceiveData($data) {
    		console.log($data);
    	}
    }(jQuery));

    But no matter what I try, I always get these errors:
    Warning: Cannot modify header information - headers already sent by ...

    The php echo is causing this, but how else are you suppose to pass the php variable to javascript?

    Is this possible?
    Thanks!

  • When you’re acf/save_post is being called it is when the post is saved. This is the way that WP works.

    1) You save your post
    2) wp-admin/post.php runs to save the post, this does not create any output
    3) ACF comes in here to save the custom fields
    4) You are redirected back to the edit page for the post

    If you want to pass data back so that is it run when the post edit page is reloaded you must save something to the database during the save, then when the post edit page is reloading you need to check for this value in the database and based on that output what you need somewhere in the page, not forgetting to remove your flag or value from the database so that it does not run on every page load.

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

You must be logged in to reply to this topic.