How to Make a WordPress AJAX Call

3 Simple Steps

Using AJAX within WordPress can be a little hard to understand. Heck, using AJAX in general can be a little hard to understand.

“Okay, so Ajax is going to call me back? Is he going to call my cellphone or the office line?”

All kidding aside, I did actually struggle a bit with learning how AJAX works within the WordPress framework.

Then I read Devin Price’s post titled Simple Ajax Example and all the lights started to flicker on. Eureka!!

By the end of this tutorial you will be making WordPress AJAX calls like a champion.

Let’s get started…

Wordpress Ajax Call

chapter 1:

What is Ajax?

AJAX is short for “Asynchronous Javascript and XML”.

Okay, what the heck does that mean?

What it means is that AJAX is not actually a programming language.

AJAX is a framework or concept that you can use to ask the backend server to do something from the frontend of your website, without reloading the page.

Awesome right!

What Is AJAX

Sending & Receiving Data

Sending and receiving data from the backend database or server is a super useful tool and AJAX does this without irritating the user by reloading the page.

This is called a Callback Function.

A good way to think about it is that the user makes a call and the server calls them back.

There are countless sites on the web using AJAX but below are some examples you are sure to have come across.

Google Suggest

Google AutocompleteThis is probably something you use every day.

Google Suggest or autocomplete is a Google search engine function that provides suggestions to users as they are typing into the search box.

You may or may not have known this but that’s AJAX sending data to and from the server in order to read your mind and automatically complete your sentence.

Okay, that’s just downright fancy pants!

Gmail

AJAX In Gmail

Ever noticed that when you click around in Gmail the page doesn’t reload?

That’s AJAX!

Google adopted AJAX for Gmail in 2004 and it’s one of the reasons why the email client took the world by storm.

It’s a feature that makes the email client super seamless and slick!

Okay, now that we have a basic understanding of what AJAX is let’s dive into learning how to make an AJAX call with WordPress!

chapter 2:

Start Learning AJAX

Making a WordPress AJAX call is a bit different then how you do it with just PHP and Javascript.

AJAX is actually built into the WordPress framework. This has a lot of advantages, but you have to use it the way it’s described in the codex.
https://codex.wordpress.org/AJAX_in_Plugins

As much as I love the WordPress codex I sometimes find that the explanations in it are written with the assumption that you already understand everything about WordPress.

Well, I say “boooooo” to hard to understand code examples.

Learn AJAX

3 Simple Steps

I have broken this section down into 3 steps that are super easy to follow.

Let’s get started on making your first WordPress AJAX call…

Step 1:

Download my example file here. Or you can use the two code sections below.

Javascript (The Call)

// This would normally be enqueued as a file, but for the sake of ease we will just print to the footer
function add_this_script_footer(){ ?>

<script>
jQuery(document).ready(function($) {

    // This is the variable we are passing via AJAX
    var fruit = 'Banana';

    // This does the ajax request (The Call).
    $.ajax({
        url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
        data: {
            'action':'example_ajax_request', // This is our PHP function below
            'fruit' : fruit // This is the variable we are sending via AJAX
        },
        success:function(data) {
    // This outputs the result of the ajax request (The Callback)
            window.alert(data);
        },  
        error: function(errorThrown){
            window.alert(errorThrown);
        }
    });   

});
</script>
<?php } 

add_action('in_admin_footer', 'add_this_script_footer');

PHP (The Callback)

function example_ajax_request() {

    // The $_REQUEST contains all the data sent via AJAX from the Javascript call
    if ( isset($_REQUEST) ) {

        $fruit = $_REQUEST['fruit'];

        // This bit is going to process our fruit variable into an Apple
        if ( $fruit == 'Banana' ) {
            $fruit = 'Apple';
        }

        // Now let's return the result to the Javascript function (The Callback) 
        echo $fruit;        
    }

    // Always die in functions echoing AJAX content
   die();
}

// This bit is a special action hook that works with the WordPress AJAX functionality. 
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

Step 2:

Copy and paste the downloaded file contents or the code sections above to your WordPress theme functions.php file.

Step 3:

Login to WordPress and you will see a popup that says “Apple”.

That’s it!! You just made your first WordPress AJAX call.

chapter 3:

The Breakdown

Okay, so that was really cool watching the little popup say “Apple”, but what the heck just happened there?

We know that the Javascript fruit variable was supposed equal “Banana”, right?

At some point the code did a fancy juke move and changed the fruit variable from “Banana” to “Apple”.

Let’s break down what happened in the code step-by-step.

AJAX Call Breakdown

Breaking It Down

  1. When you logged into the admin area WordPress loaded the Javascript in the page footer and the script executed.
  2. The Javascript then created a variable named fruit which equals “Banana”.
  3. It then sent the fruit variable to WordPress’s ajaxurl (admin-ajax.php) and told it to run the PHP function “example_ajax_request” above that you created in your functions.php.
  4. Then the fruit variable was passed to the “example_ajax_request” PHP function and processed, the result being “Apple”.
  5. PHP then made a callback to Javascript with the result.
  6. Finally, Javascript received the callback and displayed the result in a window alert.

I made a bunch of comments in the code above and in the example file as well. This should help further with understanding the process.

chapter 4:

WP AJAX Hook

Something I wanted to point out is the action hook for the PHP function in the code we just used.

WordPress uses something called hooks that allow you to fire off some code at a specific time during the page load.

When using AJAX within the WordPress framework there is a special hook.

The “wp_ajax” hook for the admin area and the “wp_ajax_nopriv” for the frontend of your website.

WordPress AJAX Hook

WordPress AJAX Hooks

add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

You will notice that the name of the function “example_ajax_request” is included in the hook. This is a good practice to remind yourself which “wp_ajax_” hook goes with which function.

The hook has to have something after wp_ajax_ in order to make it unique, so it’s a good naming convention to just add the function name you’re calling.

The above example will work in the admin area only. If you would like to use AJAX in the front-end you will have to add an extra action hook to your PHP code.

add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

You will also have to make sure the Javascript loads on the front end and that the ajaxurl is defined.

chapter 5:

AJAX Callback Function

I want to go over an AJAX callback function a bit more.

This is the core of what WordPress is doing and I think it will be helpful for us to go over the basics of where the code started.

Since I learned AJAX using jQuery we will go over this with the ajax() method.

W3School.com has a really good example, so we will give that a go.

AJAX Callback Function

jQuery AJAX Callback Function

Okay, so first let’s take a look at the code.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url: "demo_test.txt", success: function(result){
      $("#div1").html(result);
    }});
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

You can view the code in action here.

So the first thing we notice about the code is that we need to pull the jQuery library into our page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

This allows us to use the jQuery ajax() method.

Since we are trying to execute the code with a button the code looks like this:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});

The first part:
$("button").click(function()
is saying execute the ajax() method when the user clicks the button.

The part within the curly braces is the ajax bit.

It starts with the url on the server for the code we want to execute (demo_test.txt).
$.ajax({url: "demo_test.txt",
The next bit:
success: function(result){
is saying upon successfully executing this code send the result back to the user in a specific place on the page.

Below is the place on page:
$("#div1").html(result);
As you can see on the W3Schools.com example it sends back the message “jQuery and AJAX is FUN! This is some text in a paragraph.” and displays it to the user.

Pretty cool right!

This is a basic example of an AJAX Callback Function using jQuery outside of WordPress.

There are much more complicated and awesome things you can do with AJAX.

The only limit is your imagination!

Have Some Thoughts?

Please Leave A Comment Below:

I learned a lot about making a WordPress AJAX call from making this tutorial, and I hope you learned a lot as well!

Now I’d love to hear from you.

What was the #1 skill you learned from this tutorial?

Did you have a question about something that you read?

Either way, go ahead and leave a comment below right now.

Please Comment

Comments

1 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Top