Using AJAX with your WordPress Plugin

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
-
{
-
require_once("../../../../wp-config.php");
-
}
-
$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:
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:
-
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:
-
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.

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:
- Working With Events In Prototype
- Edit-in-Place with Ajax (uses Prototype)
Thank you for reading.


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/
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.
Want an avatar? Get a gravatar! • You can link to this comment
Good article. From russia, with love.
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.
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.
Want an avatar? Get a gravatar! • You can link to this comment
thank you very good.
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
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.
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
Want an avatar? Get a gravatar! • You can link to this comment
Got the solution. Ajax needs to be initialized with wp-load.php
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
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
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/
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?
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?