WordPress Responseless XHR Request Using JavaScript

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:

<?php
/**
 * 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);
    $viewsCount++;

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

    wp_die();
}
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);
}

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Wednesday, August 28, 2019 in JavaScript

Unlimited Automated Page Speed Monitoring & Tracking. Completely free.
Use SpeedFactor to track your website. It’s simple, reliable, and best of all, it’s free forever.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles


Privacy Policy