AJAX is one of the most useful solutions that allows exchanging frontend data with the backend one asynchronously (in the background) without interfering with the display and behaviour of the existing page. This article shortly describes how it was used in WordPress as usual and what are the recommendations for the latest web stack.
If you’re not familiar with how WordPress handles AJAX, you should check official docs here and here.
Infrastructure
Let’s start by creating a simple form
and action
that handles AJAX.
<form data-form-ajax>
<input type="text" name="firstname" value="Lorem" />
<input type="hidden" name="action" value="action_name" />
<button type="submit">AJAX</button>
</form>
<form data-form-fetch>
<input type="text" name="firstname" value="Lorem" />
<input type="hidden" name="action" value="action_name" />
<button type="submit">FETCH</button>
</form>
Code language: HTML, XML (xml)
/**
* @action wp_ajax_action_name
* @action wp_ajax_nopriv_action_name
*/
public function handle(): void
{
if (empty($_POST['firstname'])) {
wp_send_json_error($_POST);
}
wp_send_json_success($_POST);
}
Code language: PHP (php)
The example above prints two forms – one used for testing the $.ajax
function, the second one for fetch
. Both of them requests action_name
action handled by WordPress
that only validates if the firstname
is not empty. Simple, but enough to understand the process.
Requests
$.ajax
The most usual way for exchanging the data asynchronously is using ajax
method provided in jQuery
object. Just put the correct AJAX URL
, prepare the data and handle results using done
callback or errors using error
.
function getData(form) {
$.ajax({
url: 'http://localhost/wp-admin/admin-ajax.php',
method: "POST",
data: $(form).serialize()
})
.done(response => {
console.log(response);
})
.fail(error => {
console.error(error);
});
}
Code language: JavaScript (javascript)
Payload
The form data is prepared using serialize()
function provided in jQuery
DOM element, but you can also build your own simple key: value
object that sends specific data to the backend.
Fetch
Last time, more and more solutions are giving up using jQuery
so we need to focus on alternatives. Fortunately, there is no need to search a lot, because of the fetch
function that is supported by most of the modern browsers.
function getData(form) {
fetch('http://localhost/wp-admin/admin-ajax.php', {
method: "POST",
body: new FormData(form)
})
.then(response => {
if (!response.ok) {
throw new Error(`[${response.status}] ${response.statusText}`);
}
return response.json();
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
Code language: JavaScript (javascript)
The fetch
method looks similar to the previous one, but there are a few differences:
- Request body should be prepared using FormData or URLSearchParams (for simple text payloads).
- As per MDN
fetch
won’t handle request problems in the same way as$.ajax
handles, so additional error handling usingresponse.ok
value is required.
Payload
The example above prepares the data using FormData
that automatically populates the data based on form inputs thanks to passing form object to the constructor, but that’s not the only way for assigning the data. The other is just using append
function on FormData
object.
const data = new FormData();
data.append('firstname', 'Firstname');
data.append('action', 'action_name');
Code language: JavaScript (javascript)
ES6
The code above looks fine, but let’s try to use modern features like async ... await
that indicates asynchronicity better than callbacks.
async function getData(form) {
try {
const response = await fetch('http://localhost/wp-admin/admin-ajax.php', {
method: "POST",
body: new FormData(form)
});
if (!response.ok) {
throw new Error(`[${response.status}] ${response.statusText}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Code language: JavaScript (javascript)
Summary
As long as WordPress supports jQUery
, as long $.ajax
won’t be wrong choice, but trying to avoid technological debt from initial stages of the developments can bring you many benefits. Using fetch
doesn’t increase complication level so we should try t use it as much as it possible.
Leave a Reply