weixin_33725126 2019-02-28 11:25 采纳率: 0%
浏览 40

WP中的Ajax调用

I am creating a button to send an email to the logged-in user's branch. Just to begin coding this, I need to send an AJAX call successfully, triggering the 'success' method of the AJAX object.

I have read that the proper way is as below, using a wp_localize() function to make the admin-ajax.php file URL available in my Javascript.But it is not working.

I have tested that the enquiry() function is getting called successfully, so the script is properly enqueued.

This is my PHP plugin code:

add_action('woocommerce_after_add_to_cart_button','ajax_register_script');
function ajax_register_script()
{
    wp_register_script('mailer-script', plugins_url('/ajax-script.js', __FILE__),
        array('jquery'), '1.0', true);
    wp_enqueue_script('mailer-script', plugins_url('/ajax-script.js', __FILE__),
        array('jquery'), '1.0', true);
    wp_localize_script( 'mailer-script', 'mailer_ajax', 
        array( 'ajax_url' => admin_url('admin-ajax.php')) );
}


add_action('woocommerce_after_add_to_cart_button', 'button_function', 45);

function button_function()
{
    echo "<div class='unique' id='mail-button' onclick='enquiry()'>
  Not sure of your prescription? Click to be contacted</div>";
}

and this is my JS:

function enquiry() {

  $.ajax({
         url: mailer_ajax.ajax_url,
         type: 'post',
         data: {
            action: 'go',
           },
        success: function () {
             document.getElementById('mail-button').innerHTML =  "Thankyou for your enquiry, an email has been sent to your branch. You will be contacted shortly";
        },

    })
};

Thanks very much for any insight.

  • 写回答

1条回答 默认 最新

  • weixin_33691700 2019-03-01 12:51
    关注

    After lots of neatening up and refactoring my code is working.
    I wish i knew exactly what the problem was, as in principle the above seems to be correct. A great help was rams0610's answer on this question.

    Using AJAX in a WordPress plugin

    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办