Hi there.

This time I'm back with WP AJAX. Simple to use and easy to code.

Actually using Ajax directly into your plugin or theme is a little immature way. Cause you'll have to keep track of your files to make it work, which sometime become difficult. That's where WP_Ajax make things comfortable.

I'll share sample codes with you and will try to explain how it works.

To follow this tutorial you need to have basic understanding of AJAX, WP Plugins, WP Hooks and some other things.

To initialize AJAX let's write a sample Ajax code.

jQuery('#ajax-button').on('click', function() {
    jQuery.post(
        ajaxurl,
         {
             action: 'our_ajax_action',
             myname: 'Babar'
          },
          function( response ) {
              alert(response);
          }
    );
});

We're binding our click action on a button with id ajax-button. "ajaxurl" is defined by WP which is actually <?php admin_url().'/wp-ajax.php'; ?>. And notice the action parameter. We'll use that later.

Now filter it into the footer.

function our_footer_js_for_ajax() {
?>
<script type="text/javascript">
jQuery('#ajax-button').on('click', function() {
    jQuery.post(
        ajaxurl,
         {
             action: 'our_ajax_action',
             myname: 'Babar'
          },
          function( response ) {
              alert(response);
          }
    );
});
</script>
<?php }
add_filter('wp_footer', 'our_footer_js_for_ajax');

If you want it onto admin area, filter it in admin footer.

add_filter('admin_footer', 'our_footer_js_for_ajax');

Now time for our AJAX handler.

function our_ajax_handler_callback() {
    echo $_POST['myname'];
    die();
}

Always remember to die() or exit at the very end of the handler function. Hoot it into Ajax action. Remember our Ajax action we wrote in our JS code? We'll use it here.

add_acton('wp_ajax_our_ajax_action', 'our_ajax_handler_callback');

So it's actually Concatenate of wp_ajax_ prefix and your action data in Ajax code.

If you want to activate Ajax for non-logged in users another hook needed.

add_action( 'wp_ajax_nopriv_our_ajax_action', 'our_ajax_handler_callback' );

Just prefeix with wp_ajax_noprov_ instead of wp_ajax_.

And that's it.




What's on your mind?


7 Comments