WordPress Responseless XHR Request Using JavaScript

Ciprian on Wednesday, August 28, 2019 in AJAX and Fetching Data

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

A responseless XHR (POST) request is a request which does not require any user feedback, such as storing post views or saving data in the background. Here’s how to achieve this in WordPress using JavaScript.

Add the PHP AJAX helper function:

 * Increment post views
 * Increments post views via AJAX.
 * @return null
function example_view_increment() {
    $postId = (int) $_POST['postId'];

    $viewsCount = get_post_meta($postId, '_view_count', true);

    update_post_meta($postId, '_view_count', $viewsCount);

add_action('wp_ajax_example_view_increment', 'example_view_increment');
add_action('wp_ajax_nopriv_example_view_increment', 'example_view_increment');

Here I have created a reusable XHR wrapper for a one line usage:

 * XHR API wrapper
 * A wrapper for XHR API
 * Usage:
 * apiPostXhr(myAjaxVar.ajaxurl, 'example_view_increment', '&postId=' + postId)
 * @param url string
 * @param data string
function apiPostXhr(url, action, data) {
    let request = new XMLHttpRequest();

    request.open('POST', url, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            // Response success
        } else {
            // Response error
    request.onerror = function() {
        // Connection error
    request.send('action=' + action + data);

Modify your template to get the post ID from a data parameter, such as <div class="single-post" data-pid="75">.

And here’s how to check if the element exists and call the function:

// Increment property views
if (document.querySelector('.single-post')) {
    // Get the post ID from a data parameter (depends on your structure)
    let postId = document.querySelector('.single-post').dataset.pid;

    apiPostXhr(myAjaxVar.ajaxurl, 'example_view_increment', '&postId=' + postId);

Related posts

Leave a Reply

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