WordPress: Ajax the WordPress way

AJAX is a relatively new paradigm in the web design industry, and it most definitely is new to me. It allows you to dynamically update areas of your website with content without refreshing the page, by working directly with the server.

Many developers might not know that WordPress can handle your custom AJAX calls. By deferring all AJAX requests to admin-ajax.php in the WordPress admin folder, you can create modular chunks of AJAX code that you can tap into quickly and easily.

First, open up your functions.php file, and add this in php tags:

add_action('wp_footer', 'eps_footer');
function eps_footer() {
    echo "<script>var ajax_request_url = '".admin_url( 'admin-ajax.php' )."'</script>";

This will set a Javascript variable ajax_request_url, which will contain the path to admin-ajax.php. We’ll need this variable for our AJAX requests.

Next, we can create a simple AJAX request using jQuery. Let’s take any given Post ID, and query the database for its title. In this example, let’s just query post id #1. Also, for this example, we’re using GET. (Note: this example will not work if you dont have a post the an ID of 1. Pick an appropriate ID for your project).

$.get( ajax_request_url,
   'action' : 'get_post_title',
   'post_id' : 1
  }, function( response ){
    if ( !response.error ) {
      alert ('AJAX request made! The post title is ' + response.post_title );
    } else {
      alert ('error: ' + response.error );
},  "json" );

GET: Get, as the name suggests, should be primarily used for asking questions and receiving answers from your server. In most cases, the results from a GET request are cached, so that they’re much faster in the long run than POST. Of course this means, that GET responses should be predictable.

POST: Post requests are primarily used when you are posting new data to your server, such as updating your database, or other complicated requests that may return data which is unpredictable.

There are some main points here;

  1. We’re using a GET request
  2. We’re sending through a JSON string with the following variables:
    1. action. Will use to the action variable to hook into our AJAX handler.
    2. post_id. We will use the post_id variable in our PHP logic to query the database.
  3. The result will be stored in the response object inside the callback.
  4. Our AJAX function, below, will return a value in response.error if it can’t complete the request, so it’s good form to test for this, and alert us.

In our functions.php add this code:

add_action( 'wp_ajax_nopriv_get_post_title', 'get_post_title' );
add_action( 'wp_ajax_get_post_title', 'get_post_title' );

function get_post_title() {
  if ( isset($_GET['post_id']) ){
    $id = (int) $_GET['post_id'];
    $post = get_post( $id );
    header( "Content-Type: application/json" );
    echo json_encode( array('post_title' => $post->post_title) );

  } else {
    header( "Content-Type: application/json" );
    echo json_encode( array('error' => 'bad request') );

This may look a little complicated so let’s break it down.

First we add our hooks. In our original GET request, we passed an action variable with the value get_post_title. Notice that we use this action in the Hook Slug (first parameter of add_action). If you’re using a different action, you will need to update the Hook Slug. The second parameter of add_action is the function to call, which in this case is get_post_title().

get_post_title() checks to see if there is a post_id variable set, and if so, grabs the post from the database with the get_post() function.

Since an AJAX request is going to return some stuff, we need to set headers, and we’re using “Content-Type: application/json” for this example.

We then echo a JSON encoded array, with our return value.

jQuery will automatically turn this into an object for us to use in the callback (the response object from earlier), so that means if successful, we can expect a value in response.post_title. Lastly, we exit() out, to finish the AJAX request.

If there is a problem with the request, I have included an else statement, which gives us the ability to check for errors by using response.error in our javascript.

Hopefully but now you have the four different interactions down pat:

  1. We need to get the admin-ajax.php url available for our Javascript
  2. We nee to use the appropriate AJAX request – post or get – and send through the data we need to our admin-ajax.php url.
  3. We use WordPresses actions to catch the AJAX request and do the logic, and return the values, all based on the action parameter.
  4. We use callback functions to handle to the returned data.