1

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.

Sharkfin
  • 128
  • 1
  • 7
  • 2
    what exactly you want to do? what problem are you facing here and what have you tried so far?? – Darsh khakhkhar Feb 28 '19 at 11:29
  • I would like to make the 'success ' method fire as a result of a successful AJAX call. Sorry if that was not clear. Will edit – Sharkfin Feb 28 '19 at 14:00
  • 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. https://stackoverflow.com/questions/17855846/using-ajax-in-a-wordpress-plugin/18614405#18614405 – Sharkfin Mar 01 '19 at 12:52

1 Answers1

0

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

Sharkfin
  • 128
  • 1
  • 7