Display a function using AJAX

I am trying to display a function using AJAX using a custom plugin. But doesn’t seem to work.

My Javascript

(function($) {
$(document).on( 'click', 'a.mylink', function( event ) {
    $.ajax({
    url: testing.ajax_url,
        data : {
        action : 'diplay_user_table'
    },
    success : function( response ) {
        jQuery('#user_reponse').html( response );
    }


})
})
})(jQuery);

My PHP

add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
    wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true );
    wp_localize_script( 'test', 'testing', array(
        'ajax_url' => admin_url( 'admin-ajax.php' )
    ));
}

add_action('wp_ajax_my_action', 'diplay_user_table');

function diplay_user_table() {
    echo "function is loading in div";
}

When I click on link it just displays ‘0’. Any ideas?

3 Answers
3

You’re not hooking the function to wp_ajax correctly. You need to replace the my_action part with your action name that you’re using the in AJAX request. In your case it’s display_user_table. You also need to hook it on to wp_ajax_nopriv so that it works for logged out users. Here’s your hook with those changes:

add_action('wp_ajax_diplay_user_table', 'diplay_user_table');
add_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table');
function diplay_user_table() {
    echo "function is loading in div";
    wp_die();
}

Leave a Comment