Quick guide to WordPress AJAX.

June 23rd, 2015 | Permalink

This article in russian on habrahabr

Ok, so there is documentation page on AJAX in WordPress which is pretty definitive. This post is for the lazy. I will be as brief as I can.

So here’s how it works: (1) you define the hook function, and (2) there is a special URL, something like wp-admin/admin-ajax.php, that recieves an action request variable, and if that variable matches hook the function is called. As easy as that.

So here’s how you use WordPress’ AJAX “WordPress way”:

(1) On back-end (in your functions.php file maybe) – define a callback for the ajax action. If your AJAX is used for site frontend, (not on admin panel), you have to define two callbacks every time (one for logged-in users and one for non-logged-in. Obviousely, if ajax is called from admin panel it is called by logged in user):

// The name of ajax action in this case is do_something

add_action( 'wp_ajax_do_something',        'do_something_callback' ); // For logged in users
add_action( 'wp_ajax_nopriv_do_something', 'do_something_callback' ); // For anonymous users

function do_something_callback(){
    echo(json_encode( array('status'=>'ok','request_vars'=>$_REQUEST) )); // Here you can echo your JSON or whatever
    wp_die();                                   // AJAX callbacks should always end with wp_die
}

(2) On back-end (in your functions.php file, too) – get the url for AJAX and pass it to frontend via script tag in head. You can use the hard-coded value, of course, but it’s not recommended. To get the url you can use admin_url('admin-ajax.php') which will return an url that can be passed to front-end then. I usually simply inject a script tag into wp_head:

function js_variables(){
    $variables = array (
        'ajaxurl' => admin_url('admin-ajax.php')
    );
    echo('<script type="text/javascript">window.wp_data = '.json_encode($variables).';</script>');
}
add_action('wp_head','wgfm_head');

Such injection will be inserted after all the assets in head so you will be able to use it in your script on ready event or, maybe, even call something yourself from the injection.

(3) On front-end So now it’s relatively easy to use it in your javascript on frontend. Assuming, I am using jQuery:

jQuery(function($){
    $.ajax({
        type: "GET",
        url: window.wp_data.ajax_url,
        data: {
            action : 'do_something'
        },
        success: function (response) {
            console.log('AJAX response : ',response);
        }
    });
});

And.. that’s all. Now front-end will call the url retrieved from admin_url('admin-ajax.php'), calling it’s action do_something and recieve answer echoed by function added to wp_ajax_do_something callback. As easy as that.

Of course, there are other ways. You can include wp_load file (which is considered really bad practice). You can use localize_script to inject your ajax url into one of your scripts, but that’s just wacky IMO.

Uh, also check the protocol. If your site has wrong SSL settings but is set to work with HTTPS – the admin_url returned will be to https, but the website itself will redirect to http. Firefox will not like it, thinking you are doing cross-origin request.