当前位置: 首页 > 知识库问答 >
问题:

WooCommerce Admin Order AJAX没有得到任何响应?

巢宏富
2023-03-14

更新:问题已解决!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的admin order页面(WooCommerce>Orders>Edit)上,我添加了自定义字段,以便向订单添加自定义费用。我跟随本文添加AJAX,但它不起作用。我成功地注册了jQuery脚本add-custom-fee.js并将其排入队列,并且它在大多数情况下都能正常工作,但是我根本没有收到响应。

在admin order页面上,我在自定义字段下面添加了以下链接以触发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没有达到它。

知道是什么导致它不能工作吗?谢谢!

暂时还没有答案

 类似资料:
  • 下面是关于如何设置messenger机器人的Facebook教程-使用ngrok设置我的webhook。本地测试一切顺利,但在向bot发送消息时仍然没有收到任何响应。 韩国https://ngrok.com/ facebook教程https://developers.facebook.com/docs/messenger-platform/getting-started/quick-start/

  • 问题内容: 更新: 问题已解决!AJAX可以工作,但是我具有测试控制台日志中的功能。这是函数: 在WooCommerce的管理订单页面(WooCommerce>订单>编辑)上,我添加了自定义字段,以向该订单添加自定义费用。我正在关注这篇文章以添加AJAX,但是它无法正常工作。我成功注册并排队了我的jQuery脚本,并且在大多数情况下都有效,但是我完全没有收到响应。 在管理订单页面上,我在自定义字段

  • 当我使用下面的代码来调用一个post服务,但是我使用了 E/VOLLEY:com.android.volley.NetworkResponse@3d5dc44 我是新来的截击请帮助我相同的事情,我与改装,但我想在截击中使用。

  • 具有依赖项的Maven/Java项目: 代码: 公共类bmp_Selenium{ } 控制台输出: BrowserMob代理运行在端口:57547上启动chrome driver 2 . 33 . 506106(8 a 06 c 39 c 4582 fbfbfbab 6966 db B1 c 38 a 9173 BF B1 a 2)在端口47157上只允许本地连接。2017年11月30日下午4:4

  • 获取外部API如下图-[1]:https://i.stack.imgur.com/a28Y1.png 用作数据数组对象。 另一个物体在下面 已使用/getForObject/exchange/getForEntity,但未得到任何响应。请在底部检查我使用的方法。 现在用作数据对象的列表也没有得到任何响应- 下面是resttemplate如何调用这些- 响应obj=restTemplate。getF

  • 我在邮差7.5.0上。我从邮递员那里调用一个api,得到一个错误为“There was an error connecting to.”但当我执行从邮递员生成的curl代码时,它工作得很好(他们也在调用运行在我pc上的应用程序)。我也试图复制链接并发送给我的同事,他们也得到了正确的答复。 我提到了与这个主题相关的其他问题,并关闭了所有代理的东西,他们没有帮助。 我的应用程序有很多API,这是唯一一