Support

Account

Home Forums Backend Issues (wp-admin) How can I send an additional field during ajax requests?

Solved

How can I send an additional field during ajax requests?

  • @radgh @jonathan

    Sorry, I’m a bit of an ACF newbie so sorry if this is a silly question:

    I’ve adapted the above code for my uses and tried adding it to my main .js file, but the function doesn’t appear to be firing. It seems that typeof acf is undefined?

    When you say “THIS BLOCK MUST COME BEFORE DOCUMENT READY, AFTER ACF JS HAS LOADED.”, where should it go? I wonder if this could maybe be the issue?

  • Just in case it can help someone, I was able to accomplish this perfectly for my situation using Elliot’s select2_ajax_data filter suggestion and it’s much simpler than the other methods it seems. I have two taxonomy dropdowns and needed the 2nd one to be filtered by the value of the 1st one. @oscarfanatic ‘s solution got me pointed in the right direction and some other code I found online helped clear the rest up.

    Also want to tag @hube2 in case it can help with his awesome efforts of helping people out in the forums.

    Here’s how it works:

    add_action( 'acf/input/admin_footer', function() {
    	?>
    	<script>
    		( function( $ ) {
    			if ( typeof acf !== 'undefined' ) {
    				acf.add_filter( 'select2_ajax_data', function( data, args, elem, field, instance ) {
    					if ( 'field_648b0852a2448' === data.field_key ) {
    						data.format_id = $( '#acf-field_648b0890a2462' ).val(); // format_id is a custom property being added to the data object. It can be named whatever you want.
    					}
    					return data;
    				} );
    			}
    		} )( jQuery );
    	</script>
    	<?php
    } );
    
    add_filter( 'acf/fields/taxonomy/query/key=field_648b0852a2448', function( $args, $field, $post_id ) {
    	$format_id = $_POST['format_id'] ?? false; // $_POST['format_id'] is the custom property you created in the javascript above
    	if ( $format_id ) {
    		$args['meta_key'] = 'format';
    		$args['meta_value'] = $format_id;
    	}
    	return $args;
    }, 10, 3 );
  • By the way I also needed to clear the 2nd select’s value when the 1st select changed, so I just added this under the “acf.add_filter” javascript:

    				$( '#acf-field_648b0890a2462' ).on( 'change', function( e ) {
    	$( '#acf-field_648b0852a2448' ).val( '' ).trigger( 'change' );
    } );
Viewing 3 posts - 26 through 28 (of 28 total)

The topic ‘How can I send an additional field during ajax requests?’ is closed to new replies.