Coding

A Solution for Using Ajax in WordPress Admin

Coding,Wordpress Comments Off
Download

How to correctly use Ajax in the WordPress Administration area has been a problem that I’ve never found a complete solution for online. I’ve searched all over Google and the WordPress documentation, but there seems to be very little content on this topic. Since no one else wants to commit their time to creating and writing some example code for the use of ajax in WordPress, I decided to write my own plugin and share it with all of you.

Unlike any other solutions that I’ve seen, I’ve gone ahead and moved the javascript to a separate file for better control and readability. The one important thing you must remember with this is that the jQuery.post() function must be passed a variable name action with the name of your php callback function. For more information on how WordPress specifically handles the data with admin-ajax.php, see the documentation listed either below or in the zip file.

I wrote this code rather quickly today so I won’t bore you with the details of how the file works. It is pretty self-explanatory and is commented to help you navigate and modify the code that you see fit.

You can download the complete plugin at the top of the post and as always, let me know if you have any questions or comments.

The php file:

<?php
/*
Plugin Name: ZS Ajax Demo
Plugin URI: http://zerosignalproductions.com
Description:
Author: Zero Signal Productions
Version: 1.0
Author URI: http://zerosignalproductions.com
*/

/*
 * For more information you can visit these links
 *
 * http://codex.wordpress.org/AJAX_in_Plugins
 * http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
 * http://planetozh.com/blog/2008/04/how-to-load-javascript-with-your-wordpress-plugin/
 * http://codex.wordpress.org/Function_Reference/wpdb_Class
 * http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query
 * http://wpengineer.com/1746/wordpress-database-functions/
 * http://codex.wordpress.org/Database_Description#Table:_wp_commentmeta
 * http://amiworks.co.in/talk/simplified-ajax-for-wordpress-plugin-developers-using-jquery/
 */

define("ZS_AJAXPLUGIN_VERSION", "1.0");
define("ZS_AJAXPLUGIN_URL", WP_PLUGIN_URL ."/zs-ajaxPlugin");
define("ZS_AJAXPLUGIN_PATH", WP_PLUGIN_DIR."/zs-ajaxPlugin");

/**
 * Add a new options page to the "Settings" Panel in WordPress Admin
 * Load the external javascript file zs-ajax.js
 */
function zs_admin_menus() {
	$mypage = add_submenu_page( 'options-general.php', 'ZS Ajax Admin Demo', 'ZS Ajax Plugin', 'manage_options', 'zsajaxplugin', 'zs_ajaxDemo' );

	add_action('admin_print_scripts-'.$mypage, 'my_action_javascript');
}

add_action('admin_menu', 'zs_admin_menus');

function my_action_javascript() {
	wp_enqueue_script('my-action-javascript', ZS_AJAXPLUGIN_URL.'/zs-ajax.js');
}

/*
 * This is our admin screen. Customize your forms here. If you are using a
 * traditional html <form> tag you must define a hidden input named action with
 * the correct callback function name.
 */
function zs_ajaxDemo()
{
	?>
		<div class="wrap">
			<div id="icon-themes" class="icon32"><br></div>
			<h2>ZS Ajax Demo</h2>

			<table class="form-table">
				<tbody>
					<tr valign="top">
						<th>Ajax Request</th>
						<td>
							<input type="button" class="button-primary" id="zsSubmit" value="Send Ajax Request">
							<img src="<?php echo ZS_AJAXPLUGIN_URL ?>/ajax-loader.gif" id="zsSubmitLoader" style="display: none;" />
						</td>
					</tr>

					<tr valign="top">
						<th>Get Posts Demonstration</th>
						<td>
							<input type="button" class="button-primary" id="zsGetPosts" value="Get Posts">
							<img src="<?php echo ZS_AJAXPLUGIN_URL ?>/ajax-loader.gif" id="zsGetPostsLoader" style="display: none;" />
						</td>
					</tr>

					<tr valign="top">
						<th>Stanard Form Submit</th>
						<td>
							<form id="zs_options_form">
								<input type="text" class="regular-text" name="zs_test_text" id="zs_option" />
								<input type="button" class="button-primary" id="zsSetOption" value="Set Option" />
								<img src="<?php echo ZS_AJAXPLUGIN_URL ?>/ajax-loader.gif" id="zsSetOptionLoader" style="display: none;" />
								<input type="hidden" name="action" value="set_option" />
							</form>
						</td>
					</tr>
					<tr valign="top">
						<th>Ajax Results</th>
						<td><div id="results"></div></td>
					</tr>

				</tbody>
			</table>

		</div>
	<?php
}

/*
 * The first callback function demonstrating the use of global data and returning
 * values to the ajax request
 */
function my_action_callback()
{
	global $wpdb;
	global $userdata;
	get_currentuserinfo();

	echo "Hello ". $userdata->user_login;
	die();
}

add_action('wp_ajax_my_action', 'my_action_callback');

/*
 * The second callback function demonstrating the use of a sql query to retrieve
 * all current posts. The return data is echoed out and then set to the #results
 * div in the jQuery function.
 */
function zs_ajax_get_posts() {
	global $wpdb;

	$query = "SELECT * FROM $wpdb->posts WHERE post_status = 'publish'";
	$posts = $wpdb->get_results($query, OBJECT);

	if($posts) {
		global $post;
		foreach ($posts as $post) {
			setup_postdata($post);
			?>
				<div class="post"><?php the_title(); ?></div>
			<?php
		}
	}
	die();
}

add_action('wp_ajax_get_posts', 'zs_ajax_get_posts');

/*
 * Our final ajax demonstration showing how to insert a row into the database.
 * This function does not sanitize or return any data. You should properly check
 * the data before doing anything with the database, but I'll leave that up to you.
 */
function zs_ajax_set_option() {
	global $wpdb;

	//Get the variable
	$zs_option = $_POST['zs_option'];

	//Insert into the WordPress options table
	$wpdb->insert( $wpdb->options,
		array('option_id' => 0,
			  'blog_id' => 0,
			  'option_name' => 'zs_option_key',
			  'option_value' => $zs_option,
			  'autoload' => 'yes') );

	die();
}

add_action('wp_ajax_set_option', 'zs_ajax_set_option');

The javascript file:

jQuery(document).ready(function($) {

    /*
     * The data array if a form is not used. In this case only a button is used
     * requiring the data to be serialized manually.
     */
	var data = {
		action: 'my_action',
		whatever: 1234
	};

    jQuery("#zsSubmit").click( function() {
        jQuery("#zsSubmitLoader").show();

        jQuery.post(ajaxurl, data, function(response) {
            alert('Got this from the server: ' + response);

            jQuery("#zsSubmitLoader").fadeOut();
        });
    })

    /*
     * Once again, the 'action' variable must be set to the callback functoin
     * defined in the php file. No other data is passed with this function
     * because we are demonstrating the get_posts function.
     */
    var getPostsData = {
        action: 'get_posts'
    }

    jQuery("#zsGetPosts").click( function() {
        jQuery("#zsGetPostsLoader").show();

        //POST the data and append the results to the results div
        jQuery.post(ajaxurl, getPostsData, function(response) {
            jQuery("#zsGetPostsLoader").fadeOut();
            jQuery("#results").html(response);
        });
    })

    /*
     * In this example no data array is needed because we are serializing the
     * options form #zs_options form. To work properly a hidden input with the name
     * action must be defined with the appropriate callback function.
     */
    jQuery("#zsSetOption").click( function() {
        jQuery("#zsSetOptionLoader").show();

        //POST the data and append the results to the results div
        jQuery.post(ajaxurl, jQuery("#zs_options_form").serialize(), function(response) {
            jQuery("#zsSetOptionLoader").fadeOut();
            jQuery("#results").html(response);
        });
    })
});

Let me say thanks to Amit for giving me a starting point to work off of: http://amiworks.co.in/talk/simplified-ajax-for-wordpress-plugin-developers-using-jquery/

Share this