WordPress AJAX for Beginners

wp-ajax

In recent projects I use AJAX more, and I think it’s time to share my knowledge. This tutorial is just a simple guide to understand the basic about using AJAX in WordPress.

To follow this tutorial you will need to understand the basic of:

  1. Simple jQuery / JavaScript
  2. Simple PHP
  3. How form works
  4. Register and Enqueue Scripts in WordPress
  5. Register WordPress shortcode (example plugin)

What Is AJAX?

With JavaScript/jQuery we can manipulate DOM/HTML elements. But we can only add data that available in the DOM or add the code within the JavaScript it-self.

AJAX is a bridge to get data from PHP to the DOM without having to reload the page. For example we can pull data from the server (using PHP) when user click a button or when user scroll, etc.

This will make the user interaction flow smoother and improve user experience drastically because we no longer need to refresh the page to display new content.

smooth-af

Example:

I create an empty div:

<div id="the-empty-div"></div>

And I want to add some lorem-ipsum text inside that empty div. I can do this easily with jQuery:

jQuery( document ).ready( function($) {
    $( '#the-empty-div' ).html( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas a tortor quam...' );
});

So, from the example code above, I need to actually write the lorem-ipsum text in the JavaScript code. What if the lorem-ipsum text is a “post content” or “user data” that is dynamically managed in database ? The solution is using AJAX.

How?

Using AJAX we can submit data using POST or GET method (like in a form) to an (end point) URL and lookup that URL content as the result of the REQUEST.

jQuery(document).ready(function($) {

    $.ajax({
        type: "POST", // use $_POST method to submit data
        url: 'http://end-point-url-to/process-ajax-request.php', // where to submit the data
        data: {
            first_name : 'John', // PHP: $_POST['first_name']
            last_name  : 'Cena', // PHP: $_POST['last_name']
        },
        success:function(data) {
            console.log(data); // the HTML result of that URL after submit the data
        },
        error: function(errorThrown){
            console.log(errorThrown); // error
        }
    });  
              
});

To make it easier to understand, the AJAX code above is similar with this HTML form:

<form action="http://end-point-url-to/process-ajax-request.php" method="post">
    <input type="text" name="first_name" value="John">
    <input type="text" name="last_name" value="Cena">
    <input type="submit" value="Submit">
</form>

And in this end point “process-ajax-request.php” file, we can use this little PHP script to display the output:

<?php
$first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : 'N/A';
$last_name = isset( $_POST['last_name'] ) ? $_POST['last_name'] : 'N/A';
?>
<p>Hello. Your first name is <?php echo $first_name; ?>.</p>
<p>And your last name is <?php echo $last_name; ?>.</p>
<?php
die(); // required. To let AJAX know to end the request.

And it will display this text as final results of the request:

<p>Hello. Your first name is John.</p>
<p>And your last name is Cena.</p>

And if we want to display that HTML output in the empty box using AJAX, we can do that in AJAX “success” method:

$.ajax({
    type: "POST", // use $_POST method to submit data
    url: 'http://end-point-url-to/process-ajax-request.php', // where to submit the data
    data: {
        first_name : 'John', // PHP: $_POST['first_name']
        last_name  : 'Cena', // PHP: $_POST['last_name']
    },
    success:function(data) {
        $( '#the-empty-div' ).html( data ); // add HTML results to empty div
    },
    error: function(errorThrown){
        $( '#the-empty-div' ).html( '<p>Error retrieving data. Please try again.</p>' );
    }
});

WordPress and AJAX

Now after we get the basic understanding of how it works. Let’s move on to WordPress.

AJAX URL

WP have a great AJAX support and already built into the admin page. the URL/file to process AJAX request in WordPress is “admin-ajax.php” and is located in “wp-admin” folder.

So, the URL to this file is something like this:

http://your-site.com/wp-admin/admin-ajax.php

But, because we can install WordPress is various setup (e.g in a sub-directory), this URL is not always the same as the path above. So, it depends on how we install WordPress.

We can get this correct URL using function:

$ajax_url = admin_url( 'admin-ajax.php' );

How to get “admin-ajax.php” file URL in the JavaScript?

Everywhere in the admin pages/screen, the global JavaScript variable “ajaxurl” is available. So, if we use AJAX in the administration screen we can simply do this:

$.ajax({
    url: ajaxurl, // where to submit the data
});

How about the Front-end (Non Administration Screen)?

If it’s in the front-end, we can use wp_localize_script() to make this URL available as JavaScript variable.

wp_enqueue_script( 'my_script_handle', MY_JS_URL, array( 'jquery' ) );
wp_localize_script( 'my_script_handle', 'my_ajaxurl', admin_url( 'admin-ajax.php' ) );

To learn more about wp_localize_script() you can read Pippins tutorial: Use wp_localize_script, It Is Awesome.

And then we can use the variable like this in our JavaScript:

$.ajax({
    url: my_ajaxurl, // where to submit the data
});

AJAX Action

The next step is about how to create a PHP function to process WordPress AJAX request.

WordPress uses single file “admin-ajax.php” for everything AJAX related. To identify each request and to return the correct result/data WP uses “action” variable when submitting the data as unique identifier, and it will load an action hook based on request action.

So, in the “admin-ajax.php” file, WordPress will load function based on requested action via action hook.

Here’s an example:

$.ajax({
    url: my_ajaxurl,
    data: {
        action     : 'my_ajax_action', // load function hooked to: "wp_ajax_*" action hook
        first_name : 'John',           // PHP: $_POST['first_name']
        last_name  : 'Cena',           // PHP: $_POST['last_name']
    },
});

So for this AJAX, we can show the result in PHP function using wp_ajax_* action hook like this:

/* Load Ajax Callback to "wp_ajax_*" Action Hook */
add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );

/**
 * Ajax Callback
 */
function my_ajax_action_callback(){
    $first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : 'N/A';
    $last_name = isset( $_POST['last_name'] ) ? $_POST['last_name'] : 'N/A';
    ?>
    <p>Hello. Your First Name is <?php echo $first_name; ?>.</p>
    <p>And your last name is <?php echo $last_name; ?>.</p>
    <?php
    wp_die(); // required. to end AJAX request.
}

Actually, WordPress have two action hook for AJAX callback:

  1. wp_ajax_* (the same as above): for logged-in user.
  2. wp_ajax_nopriv_* : for logged-out user.

So if we want to display the same result to logged-in and out user, we can use this (simply use the same callback function for both hook):

add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' );

But, we can also display different messages (or login link, etc) to logged-out user, like this:

/* Load Ajax Callback to "wp_ajax_nopriv_*" Action Hook */
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_logged_out_user_callback' );

/**
 * Ajax callback for logged-out user:
 */
function my_ajax_action_logged_out_user_callback(){
    ?>
    <p>Please log in.</p>
    <?php
    wp_die(); // required. to end AJAX request.
}

If you are using WordPress AJAX in the admin panel you only need to use “wp_ajax_*” hook, because logged-out user cannot visit admin panel. But if you are using AJAX in front-end for both user and visitor (e.g display post content), you need to use both hook, “wp_ajax_*” and “wp_ajax_nopriv_*”.

You can do anything in this callback function.

  1. You can load post using “wp_query”
  2. You can retrieve options using “get_option()”
  3. You can get post meta data, or save it, etc.

Example Plugin

You can test this simple shortcode plugin using the example code above:

Download GitHub (check the branch)

It’s very straight forward. Just create a post, and add [john-cena] shortcode in it, publish, and check the result.

Important Notes

This tutorial do not cover security yet. I will write another tutorial about how to validate and secure AJAX request using nonce.

I also want to write another tutorial to explain how to use JSON data for AJAX.

Follow me on twitter @turtlepod to get update.

Comment below, let me know if I miss something OR if you want more explanation about this tutorial.

And share this tutorial if you think it’s useful 🙂

19 Comments

  1. acil kredi

    Thx so much for example. I have a question if i made costum code in wordpress. I’ll cover how to update the changes that I made?

  2. Jita

    I’m about to give up.
    I read all this and several other examples but I’m still not getting it. Implementing all of the above or using your plugin doesn’t give me any option to enter or change anything in the frontend, it just gives me “Hello…John Cena”. How can I get a form or something interacting with this?

  3. Beate

    Hi, thx, but:
    It just gives me: [john-cena]
    Yes, plugin is activ.
    No, there is no other plugin.
    WP 4.9.7., Twenty Fifteen

  4. Paul

    How can you pull data from WP database on the “process-ajax-request.php” page and send it back to frontend?

  5. Tracey

    Thank you so much for this. I tried for days to get this working before I found your tutorial. Stoked to say it’s all working great!
    I do have an issue though. I’m using this to generate a modal window that displays more info and in that I have a Gravity Form for enquiries (with ajax NOT enabled). When I submit the form I get a bad request for admin-ajax. I’d love to have ajax enabled on the form but it just hangs on send when I do that. Any idea how to get around this?

      • Tracey

        Thank you so much. First article I found showed me exactly what to do and it worked straight away. Appreciate the help.

  6. Rida Karl

    Thanks you, being a beginner in WP this article do helps me a lot. Specially on how to apply action hook for AJAX callback and how to use them.
    Please let me know how i can customize my theme using codes.

  7. Nadeem Mughal

    sir you is doing very well. very short but great content. my confusion related to ajax in wordpress cleared in just few minuts. God bless you. thanks

  8. RickH

    Very helpful; thanks.

    But would be very helpful if your theme didn’t have such a narrow content column … right now, a lot of horizontal scrolling to see the code samples (on my laptop). A wider content column would be very helpful.

  9. Tracey

    Thanks so much for this. I’m trying to use this to populate some content in a featherlight modal. It works but only on the second open.

    eg.
    Click button to open lightbox#1 – no content
    Click button to open lightbox#2 – lightbox#1 content opens

    It’s a step behind basically. Any idea how I can address this?

    I did have it working using the Foundation reveal module but that was done a couple of years ago and I am trying to unpick it to implement the new lightbox framework as Foundation is no longer being developed.

Comments are closed.