在AJAX中获取PHP值以替换输入字段值

时间:2019-05-21 16:35:22

标签: php jquery ajax wordpress

我在Wordpress中创建了一个自定义帖子类型,称为 Location / Tour ,另一个名为 Itinerary 。在我的CPT行程中,我有一些 ACF自定义字段,其中一个是 repeater字段,其中有 subfields (CPT位置/游览,标题字段,描述字段)。

我创建了一个按钮,该按钮应触发AJAX脚本,该脚本的工作是从 CPT位置/游览(标题和描述)获取值, 将它们放在 CPT行程的输入子字段(标题和描述)中。

我创建了一个PHP函数,该函数从 CPT位置/游览获取值,现在我正尝试使用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)。希望这会有所帮助。 CPT Itinerary Console log

1 个答案:

答案 0 :(得分:0)

您必须从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)
        },
    });

});