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:

 * 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);

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.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Leave a Reply

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

Related Articles

Privacy Policy