Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- The Ajax examples at https://developer.wordpress.org/plugins/javascript/ajax/
- and the subsequent PHP page are incomplete, which prevents them from working
- correctly. My full version of the examples which have worked for me.
- */
- // The HTML, added to a custom HTML block in a post
- ?>
- <form id="radioform">
- <table>
- <tbody>
- <tr>
- <td><input class="pref" checked="checked" name="book" type="radio" value="Sycamore Row">Sycamore Row</td>
- <td>John Grisham</td>
- </tr>
- <tr>
- <td><input class="pref" name="book" type="radio" value="Dark Witch">Dark Witch</td>
- <td>Nora Roberts</td>
- </tr>
- </tbody>
- </table>
- </form>
- <?php
- /*
- The relevant PHP in a plugin that I created. Does not include the comment header
- required for any plugin's main file.
- Enqueue required scripts and prepare needed data
- Script invoked by changing book selection in the above form
- */
- function my_enqueue($hook) {
- wp_enqueue_script( 'ajax-script',
- plugins_url( '/js/my-jquery.js', __FILE__ ),
- array('jquery')
- );
- $author_nonce = wp_create_nonce( 'title_example' );
- wp_localize_script( 'ajax-script', 'my_ajax_object', array(
- 'ajax_url' => admin_url( 'admin-ajax.php?my-test=hello' ),
- 'nonce' => $author_nonce,
- 'post_id' => get_queried_object_id(),
- ));
- }
- add_action('wp_enqueue_scripts', 'my_enqueue');
- /* Handle an AJAX request */
- function my_ajax_handler() {
- check_ajax_referer( 'title_example' );
- update_user_meta( get_current_user_id(), 'title_preference', $_POST['title'] );
- $args = array(
- 'tag' => $_POST['title'],
- );
- $the_query = new WP_Query( $args );
- // appends (0) to the passed title as the query normally fails to find anything
- echo $_POST['title'].' ('.$the_query->post_count.') ';
- wp_die(); // All ajax handlers should die when finished
- }
- add_action( 'wp_ajax_my_tag_count', 'my_ajax_handler' );
- add_action( 'wp_ajax_no_priv_my_tag_count', 'my_ajax_handler' );
- // Content of my plugin's /js/my-jquery.js file
- ?>
- jQuery(document).ready(function($) { //noConflict wrapper
- $(".pref").change(function() { //event
- var this2 = this; //use in callback
- $.post(my_ajax_object.ajax_url, { //POST request
- _ajax_nonce: my_ajax_object.nonce, //nonce
- action: "my_tag_count", //action
- title: this.value //data
- }, function(data) { //callback
- this2.nextSibling.remove(); //remove current title
- $(this2).after(data); //insert server response
- });
- });
- });
Add Comment
Please, Sign In to add comment