Proper way of implementing AJAX with jQuery in your WordPress plugins

AJAX LogoAJAX (Asynchronous JavaScript and XML) is web programming technique used on client side to fetch data from server side without reloading page. In this article I will write about proper way of implementing AJAX with jQuery in your WordPress plugins. Ajax has been around in WordPress code for a while now so WordPress developers have prepared a few functions and techniques to make our life a bit easier so lets get started.

In this article I will give you essential PHP and jQuery code to power single AJAX action for going from Javascript to your PHP server and returning back JSON encoded result. The first thing you need to do is to supply your Javascript with correct URL to WordPress wp-admin\admin-ajax.php file. Don't get confused with this file name, it's just that WordPress guys have implemented AJAX only in admin dashboard but admin-ajax.php is designed to be used for both front and back end AJAX in WordPress. This file does all the work, you just need to create PHP callback for your AJAX action. I usually supply my Javascript file with admin-ajax.php URL together with my other localization variables after enqueing my script like this:

1
2
3
4
5
6
7
function my_plugin_script() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('my_plugin_script', (WP_PLUGIN_URL.'/my_plugin/js/my_plugin_script.js'), array('jquery'), false, true);
    wp_localize_script('my_plugin_script', 'my_plugin_script_vars', array('ajaxurl' =>  admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'my_plugin_script');
add_action('admin_enqueue_scripts', 'my_plugin_script');

In the line 2 we will use wp_enqueue_script to enqueue jQuery library we will use for AJAX in our Javascript code. WordPress has it bundled so we don't need to give any URL because WordPress will understand what we're trying to do. Line 3 enqueues our custom Javascript file with script handle my_plugin_script named my_plugin_script.js. 3rd argument points out that this script requires jQuery library and WordPress will make sure jQuery is loaded before loading our script. 4th argument is very useful but not relevant for our application (you can check out WordPress codex file for wp_enqeue_script for more details). Last argument tells WordPres to enqueue our script in footer to make page loading faster.

After that we use wp_localize_script to attach our PHP variables to our script with script handle my_plugin_script (1st argument for wp_localize_script). This way we tell WordPress what is script handle for script that will use this variables. With 2nd argument we choose name for Javascript object that will hold our variables. In our example we will access ajaxurl variable from our Javascript code like my_plugin_script_vars.ajaxurl. The last argument for wp_localize_script is array of our variable key - value pairs, we have only one named ajaxurl and we use WordPres function admin_url('admin-ajax.php') to fetch admin-ajax.php. With 6th line we are registering this callback for use in page frontend and with 7th line of code we do the same for admin dashboard. Now let's proceed to Javascript code with our AJAX call:

1
2
3
4
5
6
7
8
jQuery.post(my_plugin_script_vars.ajaxurl, {
    action: 'my_plugin_my_action',
    js_data_for_php: 'Some Javascript data to pass to PHP AJAX handler'},
    function(php_data){
        alert(php_data.result);
    },
    'json'
);

In this example we use jQuery.post to send AJAX call using POST method to our PHP AJAX callback with handle my_plugin_my_action. We specify handle we want to pass to PHP using JSON key named action. We must remember this handle because we will use it to register our AJAX call to WordPress admin-ajax.php. This way we get right correct handler to handle our AJAX call. Since jQuery 1.4.4 you can pass any Javascript object or array to PHP and use it on the server side as regular PHP array. In this example we will pass string with property named js_data_for_php to our PHP AJAX handler. Also we must point out the format for data we will return back from PHP, it will be JSON in our case.

PHP AJAX callback is function that will be triggered by our AJAX call and this function will return data back to Javascript. I usually return my data as JSON because this way I can read just like any other regular object or array in my Javascript (like php_data.result from Javascript example above). Here's the PHP AJAX callback example:

1
2
3
4
5
6
7
8
9
10
11
function my_plugin_my_action_ajax_handler(){
    $data_from_javascript = $_POST['js_data_for_php'];
    $data_for_javascript = 'Fetched from database or somewhere else using PHP';
    $response = json_encode(array('result' => $data_for_javascript));
 
    header('Content-Type: application/json');
    echo $response;
    exit;
}
add_action( 'wp_ajax_my_plugin_my_action', 'my_plugin_my_action_ajax_handler' );
add_action( 'wp_ajax_nopriv_my_plugin_my_action', 'my_plugin_my_action_ajax_handler' );

Since we have used POST method any data from Javascript will be available in PHP $_POST superglobals array. Also we may want to fetch database or do something else Javascript can't do on it's own (that's why we use AJAX in the first place) and return result back to Javascript. After we get our data we use json_encode to prepare it for transport and use echo to print out the result. After that we ensure that our PHP script will end using exit. The last thing is to register AJAX callback handle for use by logged in users with wp_ajax prefix to our AJAX callback handle passed from Javascript using action key in our AJAX call. If we want visitors to be able to trigger this AJAX call we will register it with wp_ajax_nopriv prefix.

That's it for this interesting topic. If you need more examples you can take a look at my open source AJAX WordPress plugins Quick Chat and Quick Count. In my next article I will write more about securing your AJAX calls using WordPress nonces.

DevGenii

E-commerce is a breeze with Magento Certified Developer Plus & Zend Certified PHP Engineer nearby. Get in touch!

2 thoughts on “Proper way of implementing AJAX with jQuery in your WordPress plugins

  1. Gilbou

    Do you know if this way of working enables Google Ads to be targeted based on the ajax content too? Thank for the reply!

    Reply
    1. Marko Author

      Hello,
      from my experience Google bot triggers ajax callbacks when indexing pages. I have WP plugin Quick Count that is pure ajax plugin that shows who’s online (you can see it in sidebar here) and so far Google bot is the only bot that appears on the list. Since Quick Count does no processing on page load (it does all after page has loaded using ajax) this means Google is triggering my update users ajax callbacks.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *