1
votes

I'm developing WP plugin which when user enters ID will get post against that ID. It is working fine on admin side. I've followed this example to get data by AJAX call but now I'm trying to do it on the front end where anyone can enter ID and get a result. I've removed function which I was using to create page on admin side. Now I have 3 functions named:

  1. hello_word()
  2. ajax_script()
  3. ajax_handler()

I've tried to use following hooks to register but it was not working

  • add_action( 'admin_footer', 'ajax_script' );
  • add_action( 'wp_ajax_my_action', 'ajax_script' );
  • add_action( 'wp_ajax_nopriv_my_action', 'ajax_script' );

hello_word() function contains code for text field and button. I call hello_word() function from a template file and it's being displayed correctly, but AJAX is not working when I click button. The issue I found is that ajax_script() is not loaded and in debugging mode in source there is nothing when I click button.

So how to load ajax function correctly, while I'm calling hello_word() from a template file?

1

1 Answers

1
votes

You got things mixed up a bit.

add_action( 'wp_ajax_my_action', 'your_handler' ); and add_action( 'wp_ajax_nopriv_my_action', 'your_handler' ); are used to add function which will handle response to your ajax call for logged in and guest users respectively.

add_action( 'wp_footer', 'ajax_script' ); - front end action for footer is wp_footer and that will work only if your theme actually call it. But it's better practice to have a separate .js file with all js for your plugin instead of outputting it inline.
To enqueue your script you can use following code

function enqueue_assets()
{
    wp_enqueue_script('your_plugin_js', plugins_url('/my.js', __FILE__), array('jquery'), false, true); //true will put it into the footer
    wp_localize_script('your_plugin_js', 'your_plugin_ajax_object', array('ajax_url' => admin_url('admin-ajax.php', ((is_ssl()) ? 'https' : 'http')))); // your url for ajax call wil be available as your_plugin_ajax_object.ajax_url
    //wp_enqueue_style('your_plugin_css', plugins_url('/my.css', __FILE__)); // you can output css here too if you want
}
add_action('wp_enqueue_scripts', 'enqueue_assets');

You can call your hello_world function wherever you like.