Feature
Post

Category
Code


Using AJAX with your WordPress Plugin

How To Write a WordPress Plugin Series

This post was written as part of the How to Write a WordPress Plugin series.

More and more plugins are starting to use AJAX techniques. I personally don’t see a use for most cases of AJAX, but it may be necessary for your plugin to use AJAX to accomplish a task. This post will show you how to use AJAX with your WordPress plugin.

This post will be building on the last one where we added in a JavaScript and Stylesheet file.

Set Up a new PHP File

The Devlounge Plugin Series plugin has the following directory structure:

  • devlounge-plugin-series
    • devlounge-plugin-series.php (main plugin file)
    • js
      • devlounge-plugin-series.js.php
    • css
      • devlounge-plugin-series.css
    • php
      • dl-plugin-ajax.php (new php file for AJAX calls)

Notice I have a php extension at the end of my JavaScript file. I’ll explain the change a little later in this post.

I’ve created a new file and placed it in the php directory and have called it dl-plugin-ajax.php. I have placed the following code inside the file:

<?php
if (!function_exists('add_action'))
{
	require_once("../../../../wp-config.php");
}
if (isset($dl_pluginSeries)) {
	$dl_pluginSeries->showComments();
}
?>

This code is simple enough and is used solely for AJAX calls. It makes sure that config structure is present so we can call our class object dl_pluginSeries and reference other WordPress functions and variables. However, the showComments function hasn’t been created yet, so that is the next item on our agenda.

Set up the showComments function

The showComments function is placed inside our DevloungePluginSeries class:

function showComments() {
					global $wpdb;
					$devloungecomments = $wpdb->get_row("SELECT count(comment_approved) comments_count FROM $wpdb->comments where comment_approved = '1' group by comment_approved", ARRAY_A);
					echo "You have " . $devloungecomments['comments_count'] . " comments on your blog";
				}

You might recognize this bit of code from the database interaction post. This function outputs the number of comments made on your blog.

Allow JavaScript to Know Where Your Blog is Located

One pesky thing about AJAX is that the external JavaScript file has no idea where your blog is installed. I get around this by adding a PHP extension to my included JavaScript file so that I can access WordPress functions. Within the addHeaderCode function, I changed the code from this:

if (function_exists('wp_enqueue_script')) {
				wp_enqueue_script('devlounge_plugin_series', get_bloginfo('wpurl') . '/wp-content/plugins/devlounge-plugin-series/js/devlounge-plugin-series.js', array('prototype'), '0.1');
			}

to this:

if (function_exists('wp_enqueue_script')) {
				wp_enqueue_script('devlounge_plugin_seriess', get_bloginfo('wpurl') . '/wp-content/plugins/devlounge-plugin-series/js/devlounge-plugin-series.js.php', array('prototype'), '0.3');
			} 

The only thing I changed was the version number and added a PHP extension to the end of the JavaScript file.

Now JavaScript has a way of finding out where our blog is for AJAX calls. Let’s now set up the JavaScript.

Setting up the JavaScript

The purpose of this script (which is located in devlounge-plugin-series.js.php) is to find the blog’s URL, call the PHP file, and return a result to the user.

<?php
if (!function_exists('add_action'))
{
	require_once("../../../../wp-config.php");
}
?>
Event.observe(window, 'load', devloungePluginSeriesInit, false);
function devloungePluginSeriesInit() {
	$('devlounge-link').onclick = devloungePluginSeriesClick;
}
function devloungePluginSeriesClick(evt) {
	var url =  "<?php bloginfo('wpurl') ?>/wp-content/plugins/devlounge-plugin-series/php/dl-plugin-ajax.php";
	var success = function(t){devloungePluginSeriesClickComplete(t);}
	var myAjax = new Ajax.Request(url, {method:'post', onSuccess:success});
	return false;
}
function devloungePluginSeriesClickComplete(t) {
	alert(t.responseText);	
}

The above code does the following (keep in mind we are using Prototype):

  • Makes sure that config structure is present so we can access WordPress functions and variables.
  • After the document has loaded, the devloungePluginSeriesInit is called.
  • An event is set up for the link you added at the end of a post (line 7). If you forgot, now is the time to add the link in. Simply find a post and add this code to the bottom of it: <a href="#" id="devlounge-link">Get the Number of Blog Comments</a>
  • The absolute URL to the PHP file is found (line 12).
  • The PHP file is called (line 14).
  • The response is outputted to the user (line 18).

The Result

This next step assumes you are at the post where the link was added. When clicking on the link “Get the Number of Blog Comments“, the script uses AJAX to call a function in the DevloungePluginSeries class and returns the result to you in the form of an alert box.

AJAX Alert Box

As you can see, I don’t have many comments on my local installation.

Conclusion

This post demonstrated a very bare-bones example of how to use AJAX (using Prototype) for your WordPress plugin. Please download the code used in this post: Devlounge Plugin Series Using Ajax.

Download the Code Used In This Post

For some related reading regarding Prototype, please check out the following links:

Thank you for reading.


  1. By mark posted on June 3, 2008 at 4:50 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    can you really use the “../../../../wp-config.php” when you don’t know what their path with be? Some use wordpress/wp-content/ and some are just wp-content/

  2. By Mason posted on November 15, 2008 at 11:22 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Mark is absolutely right. The php doesn’t know where it’s installed relative to the wp-config.php file. The solution is to send the necessary path information as a POST variable when you make the AJAX request.

    This article was still very helpful. I hope Ronald will come back and edit it to make it a little better.

  3. By Alex posted on November 26, 2008 at 2:44 am
    Want an avatar? Get a gravatar! • You can link to this comment

    Good article. From russia, with love.

  4. By Kay posted on February 26, 2009 at 12:37 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    @mark If someone uses “wordpress/wp-content” the wp-config will be at “wordpress/wp-config.php”, right? so the relative path will still work.

  5. By Smartpones Review posted on April 25, 2009 at 9:17 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Thank you for good article and simple explanation. At the time I work under one plugin and each piece of information about WordPress plugins is important for me. Moreover AJAX is modern technology that I simpy have no rights to pass by.

  6. By tatil posted on July 22, 2009 at 8:27 am
    Want an avatar? Get a gravatar! • You can link to this comment

    thank you very good.

  7. By Blog Marketing posted on July 28, 2009 at 9:35 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    I am just learning to create my own wordpress plugins and this has helped me imensly

  8. By Zareef Ahmed posted on July 29, 2009 at 7:23 am
    Want an avatar? Get a gravatar! • You can link to this comment

    @mason sedning path information using a POST can open a critical security hole.

  9. By Blutarsky posted on August 14, 2009 at 10:19 am
    Want an avatar? Get a gravatar! • You can link to this comment

    Hi there my friend,
    I’ve found this interesting article when struggling to inject some content into my WordPress index.php document.

    Basically I have installed a plugin to load some content in the page above. Very slow.

    So I thought I could use the asynchronous load technique, using JQuery.

    What i did is:
    1) prepare a DIV container to hold injected data in index.php
    2) invoke jQuery from index.php to load an external php file that will call the very slow function.

    The problem is that it looks like the external php file loaded with jQuery ignores the WordPress install, as it can’t “see” WordPress; as a result when calling the function in the external php file, an error is issued: “Fatal error: Call to undefined function”.

    I have attempted succesfully to load data into the placeholder, using the external php file, using “include” and/or “require” functions, so the external php file would do the job if only jQuery (or Javascript?) would be capable to “see” WordPress data.

    I have tried to declare

    require_once(“../../../../wp-config.php”);

    but I get some errors….

    What do you think? Do you believe Javscript or jQuery are ignoring WordPress, so this is why the invoked function is failing?

    If so how to “inform” Javascript/jQuery to “see” WP?

    Thanks

  10. By Blutarsky posted on August 17, 2009 at 5:24 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Got the solution. Ajax needs to be initialized with wp-load.php

  11. By Eric Marden posted on October 20, 2009 at 3:53 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    This is absolutely the wrong way to do AJAX in a WordPress plugin.

    Do not follow these instructions. Instead study the codex carefully for the correct way of adding AJAX to your plugins: http://codex.wordpress.org/AJAX_in_Plugins

  12. By Mark posted on October 20, 2009 at 5:44 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    The method demonstrated above is overly complicated. WordPress has an AJAX handler at wp-admin/admin-ajax.php that your plugin can (should) piggy back on. This saves you the trouble of having to know where wp-config.php is (for a sufficiently flexible plugin).

    In brief:

    add_action(‘wp_ajax_my_query’, ‘my_query_handler’);
    function my_query_handler() {
    // Pull input out of $_POST and spit out your JSON, XML, etc…
    die; // die at the end so WP Core will cease trying to handle the request.
    }

    The above function would then be accessible via $blog_url . ‘/wp-admin/admin-ajax.php?action=my_query&…’.

    For additional detail:
    http://codex.wordpress.org/AJAX_in_Plugins

  13. By hokya posted on October 28, 2009 at 2:37 am
    Want an avatar? Get a gravatar! • You can link to this comment

    i have recently created new WP Plugin named AJAX Comment Page, perhaps you would try it for me on http://mr.hokya.com/ajax-comment-page/

  14. By Chris - Bermuda Triangle posted on December 3, 2009 at 8:50 am
    Want an avatar? Get a gravatar! • You can link to this comment

    @hokya Thanks hokya, by the way how can i attach google ads to wordpress? And is it even possible?

  15. By Windows Wallpapers posted on December 7, 2009 at 12:41 am
    Want an avatar? Get a gravatar! • You can link to this comment

    But, what is the benefit by using AJAX for SEO? Does Googlebot can’t read another except HTML?

  16. TrackbackBuffer Dump 16DEC07 « Feet up, eyes closed, head backWordPress Plugins - a resource list for developing your own WordPress Plugins | Independent DigitalWordpress Tutorial « Welcome To My BLOGWie programmier ich ein Wordpress PlugIn | Der Softwareentwickler BlogWordPress Plugin Development Workshop at RMI - Recap | dropthedigibomb.comNote!!! สิ่งสำคัญในการ Customize Wordpress จ้า | MyCode4UUsing AJAX with your WordPress Plugin Devlounge | Paid SurveysEssential Wordpress Plugin Development Resources, Tutorials and Guides : Speckyboy Design MagazinePHP Quebec WordPress Development | dropthedigibomb.com