Получить значения PHP в AJAX для замены значений поля ввода - PullRequest
0 голосов
/ 21 мая 2019

Я создал Пользовательский тип записи в Wordpress под названием Местоположение / Тур , а другой - Маршрут . В моем CPT-маршруте у меня есть несколько пользовательских полей ACF , одним из которых является поле повторителя , которое имеет подполей (Поле отношения для местоположения / тура CPT, Название поле, поле описания).

Я создал кнопку, которая должна запускать сценарий AJAX, задачей которого является получение значений из CPT Location / Tour (Название и описание) и поместите их в мои входные подполя (Название и описание) в моем CPT Маршруте .

Я создал функцию PHP, которая получает значения из CPT Location / Tour , и теперь я пытаюсь запустить функцию PHP с использованием AJAX.

Мне удалось заставить работать 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 голосов
/ 22 мая 2019

Вы должны вернуть данные в формате JSON из функции post_loader. Я немного прибрался, но все же, это беспорядок.

// 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)
        },
    });

});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...