UNBRANDED MANCHESTER_

What is Ajax?

AJAX is an acronym for Asynchronous Javascript and XML. AJAX is used to allow the server to communicate with the client browser, transporting information between the two after the initial page has loaded. 

The theory

Why do we use AJAX?

When a web page first loads, the server runs its PHP functions in order to generate whatever it needs to do on the frontend (or behind the scenes.) This activity takes place on the server and uses the server’s processing power.

Once the page has loaded, javascript and jQuery take over any processing that needs to happen. Unfortunately, they can only manipulate what has already been loaded. They can pull more details from the server as all processing of JS or JQ is done on the web visitors machine now.

In short, PHP and jQuery work completely independently of one another, PHP on the server and Javascript on the client’s machine.

So, what happens when we need to carry out some further PHP once the page has loaded and we want to manipulate the data on the page without reloading? AJAX.

AJAX will let us run the PHP functions in the background and then allow Javascript to manipulate the returned data in whichever way it wants, all without reloading the page (hence the A in AJAX, it’s Asynchronous, it happens at the same time.)

How do we use AJAX in Wordpress?

PHP
Decide on what variables you need to pass to the PHP function and create it as usual. In this example, we’re going to pass a value to a function to update an ACF Field in WordPress.

This is the full function we’re going to use for this example:

function add_film_token_update($updatedCount) {
$userID = $_POST[‘user_id’];
// sync user’s play count with stripe (previous total + 1)
update_field(‘credits_owed’, $_POST[‘tokens’], ‘user_’.$userID);
// echo “I did a thing”;
// print “I also did a thing”
}

add_action(‘wp_ajax_nopriv_add_film_token_update’, ‘add_film_token_update’);
add_action(‘wp_ajax_add_film_token_update’, ‘add_film_token_update’);

The first thing to take note of is how we make the function available to the Javascript for AJAX. These two lines open up the function to AJAX, you’ll always need to add these:

add_action(‘wp_ajax_nopriv_add_film_token_update‘, ‘add_film_token_update‘);
add_action(‘wp_ajax_add_film_token_update‘, ‘add_film_token_update‘);

Take note of how it’s put together, the bits highlighted in bold in the above code always need to be a duplicate of the function name.

wp_ajax_nopriv
If the function needs to be made available to non logged in users, you’ll add the line that contains wp_ajax_nopriv.

wp_ajax_
You’ll always need this line in order to get anything to work. AJAX is protected by admin in WordPress so you need to open it up for use anywhere.

Passing Values from jQuery into PHP

The full jQuery Function example is below.

$.ajax({
url: ‘https://’+window.location.host+’/wp/wp-admin/admin-ajax.php’;,
type: ‘POST’,
data: {
action: ‘add_film_token_update’, // The name of the function in PHP
user_id: userID, // A custom piece of data you want to pass to PHP
tokens: newTokenCount // A custom piece of data you want to pass to PHP
}
}).fail(function(data) { // You can call this function whatever you want, but data is standard practise
console.log(‘FAILED’);
}).success(function(data) { // You can call this function whatever you want, but data is standard practise
console.log(data);
anotherFunction(data); // Do something with the returned data
}

Take a look at the array in data, this is where we declare any info that we want to take from the client side and push into the PHP function. You can choose to put whatever you want into here and it’ll be available in PHP.

How do you get the AJAX posted values in your PHP function?
Like this:

$_POST[‘user_id’];

Or this

$_POST[‘tokens’];

Returning info from PHP to jQuery

If you echo or print anything in the PHP, you can grab it as part of the data in the success or failure function you run after AJAX has returned its state.

For example, if you wanted to return a simple message, echo or print that message or data and grab it via jQuery.

Success or Failure

Depending on how well things go with your AJAX, you’ll either return a success state or a fail state. It’s best practice to deal with both of these whenever you’re dealing with AJAX. Never assume that it’s always going to work. That would be very silly of you.

Extending and Chaining

So, if you think you’re good now, you can take this one step further and run multiple AJAX functions as a chain, with the returned values controlling the other functions that you run. How? Just add nest the whole AJAX function inside the success of another and you’ll have chained it. You could also chain to failure, but, you should never rely upon failure.

Back to Digital Guides