Most likely if you are a theme or plugin developer you will need a way to send AJAX calls to fetch new updates or to create new database records or anything else that may require a hidden backend http call.
This post will show you how that is done.
Unlike the admin area, frontend ajax in WordPress is on a tricky side.
We will design a really basic plugin to learn how this stuff actually works. I am using WordPress 3.6 beta.
First Step
We will call our plugin “Test Plugin”, so lets declare plugin meta comment
/wp-content/plugins/test-plugin/test-plugin.php
1 2 3 4 5 6 7 |
/* Plugin Name: Test Plugin Description: Shows how to put a Image Icon on post editor Version: 1.1 Author: Jaspreet Chahal Author URI: http://jaspreetchahal.org */ |
Second Step
Enqueue our JavaScript File ajax.js. Please note that we will be creating this file in a second.
/wp-content/plugins/test-plugin/test-plugin.php (append)
1 2 3 4 5 6 7 8 |
add_action('wp_enqueue_scripts', 'add_test_plugin_scripts'); function add_test_plugin_scripts(){ if(!is_admin()) { wp_enqueue_script('test-plugin', plugins_url( '/ajax.js' , __FILE__ ), array('jquery'), 1.0, true); wp_localize_script("test-plugin","test_plugin",array('ajaxurl' => admin_url('admin-ajax.php'))); } } |
Couple of points to note above are that, First we are loading our scripts for frontend only thus we are check if the Dashboard or the administration panel is attempting to be displayed with is_admin() function and Second we are localizing a variable called ajaxurl that we can access globally as text_plugin.ajaxurl
To read more on localizing some data please read this
Third Step
Lets create our ajax.js file, please note that I am creating
/wp-content/plugins/test-plugin/ajax.js
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function someUniqueFnName() { jQuery.ajax({ url: test_plugin.ajaxurl, type: "GET", data: { action: 'test_plugin' }, dataType: "html", success: function (response) { alert(response); } }); } |
As you can see that this is a really simple jQuery Ajax call. If you want to learn more on jQuery Ajax please read this. The ajaxurl
javascript global does not get automatically defined for you on frontend that is why we localized this property to be available to our function in previous step.
Fourth Step
Ok Don’t be judgemental about this one and me being lazy, but to code below should be appended to our test-plugin.php file.
/wp-content/plugins/test-plugin/test-plugin.php (append)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// this action will take care of logged in users add_action('wp_ajax_test_plugin', 'test_plugin_cb'); // this action will take care of non logged in users add_action('wp_ajax_nopriv_test_plugin', 'test_plugin_cb'); // in our case the data returned is the same for logged in or not logged in users. This is our ajax call handler function test_plugin_cb(){ echo "Yes! the ajax call was successful"; // this message will be displayed in our jacascript alert die(0); } // this is just an example but you can do whatever you like. add_filter("the_content","content_filter",10,1); function content_filter($content) { // this filter is for demo sake only and is just highlighting a point return $content."<a onclick="someUniqueFnName()" href="#ajaxcall">Click me</a>"; } |
Few things you should know
- When adding actions such as wp_ajax or wp_ajax_nopriv you should always append the action you state in your Ajax handler. In our case it is test_plugin that is why you see wp_ajax_test_plugin and wp_ajax_no_priv_test_plugin actions added to our plugin. Thus basic format of these functions is wp_ajax_nopriv_(action) and wp_ajax_(action)
- We are appending an anchor to post content just to demo if our ajax call is successful. You can do shortcodes, forms, etc etc to test this stuff out.
- Both front-end and back-end Ajax requests use admin-ajax.php
The result
You should see a link at the end of each post/page of your blog. Not Ideal but that is for demo purposes 🙂
When you click on that link you shall see this
I hope that this post will help you some how. There are some points to remembers that you can build your own Ajax handler PHP files too, so this is not the only option but this option reflects the WordPress way. Advantage of this is that you will have access to important initializations such as $wpdb etc
If I am missing a point or two please feel free to add your insights via comments
Cheers
I tried to activate the above plugin.
But I get the following erroron the plugin activation page:
Parse error: syntax error, unexpected ‘someUniqueFnName’ (T_STRING) in /home/greentes/public_html/wp-content/plugins/test-plugin/test-plugin.php on line 38
Have you got any ideas please?