【问题标题】:WooCommerce Admin Order AJAX Not Getting Any Response?WooCommerce 管理员命令 AJAX 没有得到任何响应?
【发布时间】:2020-03-31 15:06:36
【问题描述】:

更新:问题已解决! AJAX 工作,但我有函数 debug_to_console 用于测试 echo 到控制台日志。这是函数:

/* This is a function to print data to web browser console **
** Use debug_to_console( $data ); to print */
function debug_to_console( $data ) {
  $output = $data;
  if ( is_array( $output ) )
  $output = implode( ',', $output);

  echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>";
}

在 WooCommerce 的管理订单页面(WooCommerce > 订单 > 编辑)上,我添加了自定义字段以向订单添加自定义费用。我正在关注this article to add AJAX,但它不起作用。我成功注册了我的 jQuery 脚本 add-custom-fee.js 并将其加入队列,并且大部分情况下它都可以正常工作,但我根本没有收到任何响应。

在管理订单页面上,我在自定义字段下方添加了以下链接以触发 AJAX:

$nonce = wp_create_nonce('add_custom_fee_nonce');
$link = admin_url('admin_ajax.php?action=add_custom_fee&post_id=' . $order->id . '&nonce=' . $nonce );
echo '<a class="add-custom-fee" data-nonce="' . $nonce . '" data-post_id="' . $order->id . '" href="' . $link . '">Add fee?</a>';

这是我注册脚本并将其加入队列的方式:

add_action('admin_enqueue_scripts', 'load_add_custom_fee_ajax_js');
function load_add_custom_fee_ajax_js( $hook ) {

  // Deprecated; append datetime as version number of script
  //$my_js_ver = date("ymd-Gis", filemtime( plugin_dir_path( __FILE__ ) . 'js/add-custom-fee.js' ));

  // Only register and enqueue on order edit page
  if ( 'post.php' == $hook || 'edit.php' == $hook ) {

    global $post;

    if ('shop_order' === $post->post_type) {
      wp_register_script( 'add-custom-fee', get_stylesheet_directory_uri() . '/js/add-custom-fee.js', array('jquery'), 1.0, true );

      // enqueue the JavaScript file
      wp_enqueue_script( 'jquery' );
      wp_enqueue_script( 'add-custom-fee');

      // localize the script to reference admin-ajax URL
      wp_localize_script( 'add-custom-fee', 'myAjax', array( 'ajaxurl' => admin_url('admin-ajax.php') ) );
    }
  }
}

这是我的 jQuery 脚本:

jQuery(document).ready(function () {
  console.log("Hello world! Add custom fee JS script enqueued!");
});

/* START of code to add a custom fee to the order in admin and recalculate */
jQuery(document).ready(function ($) {

  $('.add-custom-fee').click( function(e) {
    e.preventDefault();

    console.log("Add fee toggle change detected! Grabbing values...");

    // var ajaxurl = 'https://staging1.orderpantry.com/wp-admin/admin-ajax.php';
    var add_fee_toggle = $("input[name='add_fee_toggle']:checked").val();
    var add_fee_name = $("input[name='add_fee_name']").val();
    var add_fee_percentage = $("input[name='add_fee_percentage']").val();

    console.log("Toggle? " + add_fee_toggle + ". Fee name: " + add_fee_name + ". Fee percentage: " + add_fee_percentage + "%");

    // Remove cookie and do not apply fee
    if (add_fee_toggle == '') {

      // Clear the fee fields
      $("input[name='add_fee_toggle'][value='']").prop('checked', true);
      $("#add_fee_name").val('');
      $("#add_fee_percentage").val('');

      console.log('Fee not added!');
      $('button.calculate-action').trigger('click'); // <-- trigger recalculate order
      //$('button.save-action').trigger('click');       <-- trigger saving order
    } else {

      order_id = $(this).attr('data-post_id');
      nonce = $(this).attr('data-nonce');

      console.log("This order's ID is " + order_id + " and its nonce is " + nonce);

      // Push fee values to AJAX function
      $.ajax({
        type: 'post',
        dataType: 'json',
        url: myAjax.ajaxurl,
        data: {
          action: 'create_fee_object',
          order_id: order_id,
          nonce: nonce,
          add_fee_toggle: add_fee_toggle,
          add_fee_name: add_fee_name,
          add_fee_percentage: add_fee_percentage
        },
        success: function(response) {
          if ( response.type == 'success' ) {
            console.log('Success! AJAX request received!');
            // Trigger the order to recalculate on success
            $('button.calculate-action').trigger('click');
          } else {
            alert('An error has occurred while adding your fee.');
            $('button.calculate-action').trigger('click');
          }
        }

      });
    }
  });
});

我没有收到任何响应,无论是成功还是失败。代码似乎刚刚在这里停止工作。

这是我的 PHP 代码:

add_action('wp_ajax_create_fee_object', 'create_fee_object');
add_action('wp_ajax_nopriv_create_fee_object', 'please_login');
function create_fee_object() {

  if ( !wp_verify_nonce( $_REQUEST['nonce'], 'add_custom_fee_nonce' ) ) {
    exit("Unsecured access detected!");
  }

  debug_to_console( "Add fee data reached AJAX function!" );

  // Check if action was fired via Ajax call. If yes, JS code will be triggered, else the user is redirected to the post page
  if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $result['type'] = 'success';
    $result = json_encode($result);
    echo $result;
  } else {
    header("Location: ".$_SERVER["HTTP_REFERER"]);
  }

  die();
}

function please_login() {
  alert("You must log in to do this.");
  die();
}

我不认为函数 create_fee_object 工作或 AJAX POST 没有达到它。

知道是什么导致它无法工作吗?谢谢!

【问题讨论】:

  • 将以下内容添加到传递给 $.ajax 函数的对象中:完成:function (jqXHR, textStatus) { console.log(textStatus); }
  • ...或检查浏览器调试控制台中的网络选项卡。我敢打赌 $.ajax 函数确实会触发,但会出错。您在成功回调中检查 response.type == 'success' - 这可能是您感到困惑的地方 - 此响应对象来自您的 PHP 代码(而不是来自 jQuery),因此它并不表示成功/失败$.ajax 请求本身。
  • @mattavatar 你是对的,ajax 确实有效,在网络选项卡中我确实看到了 200 OK。我在我的代码中添加了用于创建费用对象并将其添加到订单中并且它有效!但是,我仍然无法获得可以触发重新计算订单的成功响应(使用$('button.calculate-action').trigger('click');)。我将 complete:function 添加到我的 ajax 函数中,但没有发生任何不同。如何获得成功响应?
  • 仍在调试:在 create-fee_object() 函数的顶部添加以下内容: wp_send_json_success( array( 'type' => 'success' ) );死();
  • ohhh... 你从这里获取了 debug_to_console 函数:stackoverflow.com/a/20147885/2540235 ???是的,这会弄乱您的响应,因为它会返回包含在脚本标签中的文本……哇,这真的会与 XHR 混淆,可能会导致完整回调的跳过!我认为您发现了一个非常巧妙的错误...

标签: php jquery ajax wordpress woocommerce


【解决方案1】:

答案:删除debug_to_console( "Add fee data reached AJAX function!" );

假设您从 this SO post 复制了 debug_to_console,那么您在预期的响应内容上方打印了一个 &lt;script&gt; 标记,因此您不仅不会在回调中看到预期的数据,而且您的 success 回调将开火。为什么?因为您已经告诉 $.ajax 期待 JSON(通过 dataType: 'json'),但是 jQuery 在尝试将您返回的内容解析为 JSON 时抛出错误。

【讨论】:

  • 谢谢@mattavatar!
猜你喜欢
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 2013-12-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
相关资源
最近更新 更多