Support

Account

Home Forums Backend Issues (wp-admin) Update ACF fields in WordPress admin using Ajax Reply To: Update ACF fields in WordPress admin using Ajax

  • Thank you for reply. If i correct understand, i write this code in funtions.php

    add_action( 'wp_ajax_my_acf_update2', function(){
      // Get post id
      $post_id = $_POST['post_id'];
      // Get id another post from the relation field
      $another_post_id = get_field('Blocks-FirstSlide-copyBlock', $post_id );
      // Getting data
        $source_fields = get_field_objects($another_post_id);
        //Creating response
        $response = array();
        foreach ($source_fields as $field) {
      $response[$field['key']] = $field['value'];
        }
        echo json_encode($response);
        exit;
        });

    and this code in script:

    jQuery( function ( $ ) {
      $ ('.acf-field-64647e4980e03').click( function(){
        var input = $(this);
        var post_id = $('#post_ID').val();
        $.ajax({
          type : 'POST',
          url : ajaxurl,
          data:{
            action:'my_acf_update2',
            post_id: post_id
          },
          success: function(data) {
            for (var key in json) {
      var field = acf.getField(key);
      field.val(json[key]);
    }
          }
        });
      } ); 
    } );

    Result:
    Uncaught ReferenceError: json is not defined
    at Object.success

    About button you give good idea, i change trigger next time.
    Can you help me with code above?