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:

add_acction('wp_ajax_alert_message','get_alert_message');
add_acction('wp_ajax_nopriv_alert_message','get_alert_message');
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!
      exit;
}

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:

add_action('init','my_alert_script');
function my_alert_script() {
       wp_enqueue_script('myalertjs','path/to/js/myalert.js',array('jquery'));
}

And our JavaScript……

(function($){

$(document).ready(function(){
    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
    $('#mybutton').click(function(){
           //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"
           $.post(ajaxurl,data,function(resp){
                   alert(resp.message + ' ' + resp.user);
           },'json');
    });
});

})(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!