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.