Implementing AJAX in WordPress
There are plenty of sources on the Web that cover this topic, when I first began developing for WordPress I was left scratching my head understanding methods that made the process easy and within WordPress best practices. Finally I came up with the most simpliest and standard way of implementing AJAX in WordPress.
NOTE: This article assumes you have a good understanding of jQuery and AJAX (and of course, PHP)
Using Ajax on the Administration Side
Since WordPress 2.8, ajaxurl is always defined in the admin header and points to admin-ajax.php
Here’s a short example. All this will be in one file. First, add some javascript that will trigger the AJAX request:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <script type="text/javascript" > jQuery(document).ready(function($) { // the value of 'action' is the key that will be identified by the 'wp_ajax_' hook var data = { 'action': 'my_action', 'message': 123 }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php $.post(ajaxurl, data, function(response) { // Output the response which should be 'Hellow World' alert(response); }); }); </script> |
Then, set up a PHP function that will handle the request:
1 2 3 4 5 6 7 8 9 10 11 12 |
Using Ajax on the Front-end Side
By default, the wp_ajax_ displays the output only to logged-in users, if you want it to fire on the front-end for both visitors and logged-in users, simply add this additional hook into your action handler:
1 | add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' ); |
Unlike on the admin side, the ajaxurl javascript global does not get automatically defined for you, a quick fix for this is to create a variable which contains the admin-ajax.php
1 2 3 4 5 | var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; $.post(ajaxurl, data, function(response) { // Output the response which should be 'Hellow World' alert(response); }); |
Error Return Values
If the Ajax request fails in wp-admin/admin-ajax.php, the response will be -1 or 0, depending on the reason for the failure. Additionally, if the request succeeds, but the Ajax action does not match a WordPress hook defined with add_action(‘wp_ajax_(action)’, …) or add_action(‘wp_ajax_nopriv_(action)’, …), then admin-ajax.php will respond 0
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me