Oneupweb : Ajax in WordPress

Ajax in WordPress is all kinds of easy. We are going to give an example in the functions.php file, but you can just as easily implement this inside of a plugin. Ajax functionality is accomplished like many other things in WordPress, through the use of actions and callback functions. Let’s give the example of outputting a simple message sent from the server:

function get_alert_message() {
     $response = array(
            'user' => 'Brian',
            'message' => 'Hello'
      header('Content-Type: application/json');
      echo json_encode($response);
      //make sure you exit otherwise further output will be processed and mess up your response!

The little snippet above will put a hook in place for your JavaScript to make a call to. The actions we are adding to are “wp_ajax_alert_message” and “wp_ajax_nopriv_alert_message”. The “alert_message” part of those actions are what we will reference in our JavaScript. We prefix our action name with “wp_ajax_” and “wp_ajax_nopriv_” to say we want logged in users (wp_ajax_) and non logged in users (wp_ajax_nopriv_) to be able to see this ajax in action.

Let’s queue up our JavaScript like so:

function my_alert_script() {

And our JavaScript……


    var data = {
          action:"alert_message" //look familiar? this comes after our wp_ajax_ and wp_ajax_nopriv_ actions we added in functions.php

    //lets talk to the server when we click a button
           //ajaxurl is a global JavaScript variable WordPress provides. neat huh?

           //if for some reason you are getting ajaxurl is undefined, it points to /wp-admin/admin-ajax.php
           //var ajaxurl = "/wp-admin/admin-ajax.php"
                   alert(resp.message + ' ' + resp.user);

})(window.jQuery); //easy workaround to use the $ factory we all love so much

Try it out!

Naturally I can’t wait to see how you use your new found knowledge of ajax in WordPress to take WordPress functionality to the next level!