AJAX in WordPress Plugins

This article, aimed at plugin developers, describes how to add Ajax to a plugin.

Step 1:

Create a javascript file call my_query.js to handle you request and save it on js(js/my_query.js) folder of your plugin.

// JavaScript Document
function myfunction(id)
{
 var ajaxval = id;
 $.ajax({
    type: 'POST',
    url:  ajaxvoteajax.ajaxurl,
    data: {
      'action': 'my_action',
      'val': ajaxval
      },
    context: document.body,
    success: function(data, textStatus, XMLHttpRequest){
      var data = data; 
       $('#model').html(data);    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert(errorThrown);
    },
    complete: function(XMLHttpRequest, status) {
          }
 });
}

Note: Replace action parameter by your action. In this example I used “my_action” as the action.

Step 2:

With external files, we must enqueue them in PHP so they are included on the page

<?php
add_action('wp_enqueue_scripts', 'my_enqueue');
function my_enqueue()
{
wp_enqueue_script('myenqueue', plugins_url('/js/my_query.js',__FILE__), array('jquery'));
wp_localize_script( 'myenqueue', 'ajaxmy_enqueuejax', array( 'ajaxurl' => admin_url('admin-ajax.php',__FILE__) ) );
}
?>

Step 3:

Now do the required operation.

// Same handler function...
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback() {
	global $wpdb;
	$whatever = intval( $_POST['whatever'] );
	$whatever += 10;
        echo $whatever;
	die();
}

Note: Use same action name for the function. In this example I used my_action. So just replace “my_action” from “function my_action_callback()” function.

Step 4:

So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:

add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');

Note: ‘my_action_callback’ is the function name here. Just replace the”my_action” by your action from “wp_ajax_nopriv_my_action” and “wp_ajax_nopriv_my_action” hooks.

Advertisements

One thought on “AJAX in WordPress Plugins

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s