HTML5 Zone is brought to you in partnership with:

Paulund is a website dedicated to writing tutorials and code snippets about Web Development, the main subjects are PHP, Wordpress, jQuery, CSS3 and HTML5. Paul is a DZone MVB and is not an employee of DZone and has posted 137 posts at DZone. You can read more from them at their website. View Full User Profile

Using AJAX In WordPress

08.29.2014
| 3758 views |
  • submit to reddit

In the following tutorial we are going to learn how you can use AJAX in WordPress to run your own functions. The way this works in WordPress is by allowing you to attach your own actions that you can access from an AJAX request to change the content on the page.

What Is AJAX?

Normally on a webpage you have to wait for the server to load the content of the web page, after the load the only way you can change the content on the page is with JavaScript code. JavaScript is a client-side language that will not run any server side tasks, therefore you can not make another request to the server to change the content unless you refresh the page, but this could change the content in other areas of the page.

AJAX stands for Asynchronous JavaScript and XML, allowing you to make asynchronous HTTP requests to the server once the page has already loaded. It will use JavaScript to make a request to a URL allowing you to POST additional data to the server, the output of this server request is then processed and stored in the JavaScript so that you can change the content of the page.

WordPress has AJAX already built into the core and requires you to submit this information to a certain URL in the WordPress application, the reason you can't use any URL with WordPress AJAX is because WordPress needs to be instantiated before you can access data in the WordPress database.

AJAX In The Admin Area

If you have previous experience using AJAX, then using it in the WordPress admin area is relatively straight forward. As AJAX is already built into the core you can simply piggy back on this.

First you need to create a JavaScript file that you will use to make the AJAX request and handle the data returned, then enqueue this in the admin screens. Create a WordPress plugin or add the following to your theme functions.php file.

add_action( 'admin_enqueue_scripts', 'add_ajax_javascript_file' );
function add_ajax_javascript_file()
{
    wp_enqueue_script( 'ajax_custom_script', plugin_dir_url( __FILE__ ) . 'ajax-javascript.js', array('jquery') );
}

This will add our JavaScript file to the admin pages in WordPress admin area, now we can add the jQuery required to submit the ajax request.

jQuery(document).ready(function($) 
{
    var data = {
        'action': 'get_post_information',
    'post_id': 120
    };

    $.post(ajaxurl, data, function(response) {
        alert('Server response from the AJAX URL ' + response);
    });
})

The above JavaScript will be added to our JavaScript file and will use jQuery to post data to the ajaxurl variable. This variable is a global variable setup by WordPress that will post to the admin-ajax.php file. This file instantiates WordPress and will run any actions setup in WordPress.

The data that we are submitting is a JavaScript object with the fields action and post_id in it. The action is the WordPress action code we want to run when submitting this request, the other data is also posted so that we can consume this in the server-side code.

Now we need to setup the WordPress action that will get called on this AJAX request.

<?php 

add_action( 'wp_ajax_get_post_information', 'ajax_get_post_information' );

function ajax_get_post_information() 
{
    if(!empty($_POST['post_id']))
    {
        $post = get_post( $_POST['post_id'] );

        echo json_encode( $post );
    }   

    die();
}

The above code should be added to either the new plugin or to the functions.php file so that the action can be registered. We need to use the action of "wp_ajax_{action}" with {action} being the one defined in the JavaScript file. In the callback function we then get the posted post_id and search for the post using the get_post() function, then we can echo a JSON object of the post data for the JavaScript to pick up the response. On the response of the AJAX we can now add this post information to any part of the page we want.

AJAX In The Frontend

AJAX on the frontend of your website is a bit more complicated but is still do-able if you understand the concepts of the above code.

The first thing you need to be aware of is the ajaxurl JavaScript variable is not defined on the frontend so you need to define this namespace object when you load your JavaScript file by using the function wp_localize_script()

add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file' );
function add_frontend_ajax_javascript_file()
{
    wp_localize_script( 'frontend-ajax', 'frontendajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
    wp_enqueue_script( 'ajax_custom_script', plugin_dir_url( __FILE__ ) . 'ajax-javascript.js', array('jquery') );
}

In the admin area there is only one AJAX action that you need to use wp_ajax_{action} on the frontend you can use two AJAX actions, wp_ajax_{action} and wp_ajax_nopriv_{action} the difference being that the current user doesn't need to be logged in to run the AJAX action. Therefore if the user isn't logged in it will run the function attached to wp_ajax_nopriv_ but if the user is logged in it will run the function attached to wp_ajax_

<?php 

add_action( 'wp_ajax_get_post_information', 'ajax_get_post_information' );
add_action( 'wp_ajax_nopriv_get_post_information', 'ajax_get_post_information' );

function ajax_get_post_information() 
{
    if(!empty($_POST['post_id']))
    {
        $post = get_post( $_POST['post_id'] );

        echo json_encode( $post );
    }   

    die();
}

AJAX Errors

If the AJAX action fails then it will return one of two values either 0 or -1.

If the action that you are requesting doesn't exist then the AJAX response will return 0. To fix this error you need to make sure that you have defined your wp_ajax_ action correctly.

If the request fails to call the URL correctly it will return with a -1.

 

 

Published at DZone with permission of Paul Underwood, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)