phpjqueryajaxwordpressqtip

Qtip and ajax in Wordpress - action not working


I'm trying to integrate the QTip jquery tooltip in my Wordpress site, using Ajax to trigger a tooltip with some information pulled from a custom database table.

I've added the enque and action stuff to my function.php:

function enqueue_scripts_styles_init() {
  wp_enqueue_style('qtip', 'http://www.my-site.com/wp-content/themes/my-theme/qtip/jquery.qtip.min.css', null, false, false);
  wp_enqueue_script('qtip', 'http://www.my-site.com/wp-content/themes/my-theme/qtip/jquery.qtip.min.js', array('jquery'), false, true);
  wp_enqueue_script('qtipCall', 'http://www.my-site.com/wp-content/themes/my-theme/qtip/qtipcall.js', array('jquery', 'qtip'), false, true);
  wp_localize_script( 'qtipCall', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('init', 'enqueue_scripts_styles_init');

function ajax_action_stuff() {
  global $wpdb;
  $hero = $_POST['who'];
  $results = $wpdb->get_row( $wpdb->prepare ('SELECT * FROM wp_herotable WHERE Name = %s', $hero) );
  $hero_bio = $results->Bio;
  echo $hero_bio;
  wp_die();
}
add_action( 'wp_ajax_ajax_action', 'ajax_action_stuff' );
add_action( 'wp_ajax_nopriv_ajax_action', 'ajax_action_stuff' );

This is my qtipcall.js:

jQuery(document).ready(function( $ ) {
$('[tip-hero').each(function() {
    $(this).qtip({
        content: {
            text: function(event, api) {
                $.ajax({
                url: ajax_object.ajaxurl,
                type: 'POST',
                action: 'ajax_action',
                data: {who: $(this).attr("tip-hero")},
            })
                .then(function(content) {
                    // Set the tooltip content upon successful retrieval
                    api.set('content.text', content);
                }, function(xhr, status, error) {
                    // Upon failure... set the tooltip content to error
                    api.set('content.text', status + ': ' + error);
                });

                return 'Loading...'; // Set some initial text
            }

        },

        style: { 
        classes: 'qtip-dark qtip-rounded qtip-shadow'
        }
    });
});

});

Finally, my page:

<a hfer="#" tip-hero="Joan of Arc">Joan of Arc</a>

The result is a cool tooltip with a 0 in it! I've checked the admin-ajax.php and the zero is coming from:

// Require an action parameter
if ( empty( $_REQUEST['action'] ) )
die( '0' );

So I think there is a problem with my action call but I really can't understand what it is.

Any help will be appreciated.

Thanks.


Solution

  • Change your ajax to send the action value:

       data: {who: $(this).attr("tip-hero"),action: 'ajax_action'},