【问题标题】:Get PHP values in AJAX to replace input field values在 AJAX 中获取 PHP 值以替换输入字段值
【发布时间】:2019-10-08 02:42:40
【问题描述】:

我在 Wordpress 中创建了一个名为 Location/TourCustom Post Type,另一个名为 Itinerary。在我的 CPT 行程中,我有一些 ACF 自定义字段,其中一个是具有 子字段(CPT 位置的关系字段/ Tour、Title 字段、Description 字段)。

我创建了一个按钮,该按钮应该触发一个 AJAX 脚本,该脚本的任务是从 CPT Location/Tour(Title and Description) 和 将它们放在我的 CPT Itinerary 中的输入 subfields(Title and Description) 中。

我创建了一个从 CPT Location/Tour 获取值的 PHP 函数,现在我正在尝试使用 AJAX 运行 PHP 函数。

我能够让 AJAX 正常工作,并且我在 ResponseText 下的 控制台日志 中获得了值。

现在是我正在努力的部分。我需要在 JS 中将 每个值 设置为 单独的变量,以便我可以用新的值替换 输入字段值,但不幸的是我没有不知道怎么做。 我已经尝试了几乎所有东西,我认为我已经接近答案了,但我错过了一些东西。 :(

这是我的 post-value-loader.php

<?php
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');

function post_loader($field) {

  $post_id = $_POST["post_id"];

  $args = array(
    'p' => $post_id,
    'numberposts'=> -1,           // Fetch all posts...
    'post_type'=> 'location_tour',      // from the 'location_tour' CPT...
  );

  $location = new WP_Query( $args );

  if ( $location->have_posts() ) : while ( $location->have_posts() ) : $location->the_post();

        $title = the_field('title'); //The Title field value that we need
        $description = the_field('description'); //The Description field value that we need
        wp_reset_postdata();
      ?> 
    <?php endwhile; endif; ?>
<?php add_action('acf/prepare_field/name=default_tour', 'post_loader'); ?>
<?php }


// BUTTON TO RUN AJAX
function my_acf_prepare_field($field) {
  echo '<div class="acf-field"><button type="submit" id="data_fetch" class="button acf-load-default-tour-values">Load default value</button></div>';
    return $field;
}
add_action('acf/prepare_field/name=default_tour', 'my_acf_prepare_field');


// ADD SCRIPT TO WORDPRESS ADMIN AJAX
function js_data_fetch() {
  wp_enqueue_script ("ajax-data-fetch", get_stylesheet_directory_uri() . "/inc/assets/js/data-fetch.js", array('jquery')); 
  //the_ajax_script will use to print admin-ajaxurl in data-fetch.js
  wp_localize_script('ajax-data-fetch', 'the_ajax_script', array('ajaxurl' =>admin_url('admin-ajax.php')));
} 
add_action("admin_enqueue_scripts", "js_data_fetch");
?>

这是我的 data-fetch.js (注意:我不是 JS 人 :( )

jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
    dohvati.preventDefault();

    var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field

    jQuery.ajax({
        url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
        type: "POST",
        dataType: 'json',
        data: {
            action: 'post_loader', // This is the name of the php function
            post_id: post_id,
        },
        success: function(data){
            console.log(data)
        },
        error: function(error){
            console.log(error)
        },
    });
    jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(title); //This is replacing the title field - but the variables are missing
    jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(description); //This is replacing the description field - but the variables are missing
});

这里还有两张来自 CPT 行程编辑器 (https://imgur.com/kFImdpe) 的图片,其中包含字段和我的控制台日志 (https://imgur.com/wwxKXQP)。希望这会有所帮助。

【问题讨论】:

    标签: php jquery ajax wordpress


    【解决方案1】:

    您必须从 post_loader 函数以 JSON 格式返回数据。我已经清理了一点,但仍然是一团糟。

    // LOAD DEFAULT VALUES FROM DEFAULT TOUR
    add_action('wp_ajax_post_loader', 'post_loader');
    
    function post_loader() {
    
        $post_id = $_POST["post_id"];
    
        $args = array(
            'p' => $post_id,
            'numberposts'=> -1,           // Fetch all posts...
            'post_type'=> 'location_tour',      // from the 'location_tour' CPT...
        );
    
        $location = new WP_Query( $args );
    
        if ( $location->have_posts() ) : 
            while ( $location->have_posts() ) : 
                $location->the_post();
    
                $title = the_field('title');
                $description = the_field('description');
    
                // You have to return data as json
                wp_send_json([
                    'title' => $title,
                    'description' => $description
                ]);
    
                //wp_reset_postdata();
            endwhile; 
        endif;  
    
        // Why do you need this inside this function?
        // add_action('acf/prepare_field/name=default_tour', 'post_loader');  
    
    }
    

    JS

    jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
        dohvati.preventDefault();
    
        var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
    
        jQuery.ajax({
            url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
            type: "POST",
            dataType: 'json',
            data: {
                action: 'post_loader', // This is the name of the php function
                post_id: post_id,
            },
            success: function(data){
                console.log(data)
    
                jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(data.title); //This is replacing the title field - but the variables are missing
                jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(data.description); //This is replacing the description field - but the variables are missing
    
            },
            error: function(error){
                console.log(error)
            },
        });
    
    });
    

    【讨论】:

    • 非常感谢。您的代码有效!我能够解决这个问题。另外,我在将值分配给变量时犯了一个错误。它应该是 $variable = get_field('field') 而不是 the_field('field') 因为 get_field() 用于获取值而 the_field() 仅用于打印出来。
    • ps。很抱歉发布了不必要的代码,我现在已经清理了它:D
    猜你喜欢
    • 2023-04-09
    • 2012-11-07
    • 2014-08-22
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    相关资源
    最近更新 更多